Telegram Group & Telegram Channel
[[lifetimebound]]

В компиляторы C++ потихоньку приходят интересные фичи с memory safety, в этот раз поговорим о [[clang::lifetimebound]]. Он предназначен для того, чтобы показать, что жизнь возвращаемого объекта может зависеть от жизни аргумента

Я частенько видел код в духе

const std::string& s = StatusOrProtobuf()->field_value();

Где StatusOrProtobuf возвращает absl::StatusOr<Proto>, где мы знаем, что статус будет всего OkStatus.

И в этот момент я всегда задавался вопросом, а верно ли, что это просто неправильно? StatusOrProtobuf() будет же локальной переменной, в итоге мы берем ссылку на объект внутри локальной переменной, что вроде бы undefined behavior, так как локальная переменная разрушится.

Компиляторы и санитайзеры могут это не поймать так как примеры могут быть более интересными в духе


template<typename T, typename U>
const U &get_or_default(const std::map<T, U> &m,
const T &key,
const U &default_value);

В итоге если вернётся default value, то писать в духе

const std::string &val = get_or_default(m, "foo"s, "bar"s);

некорректно. В тестах можно забыть протестировать default_value, а в проде выстрелит.

В clang привнесли атрибут [[clang::lifetimebound]], который находит всякие такие баги на этапе компиляции. Можно писать


template<typename T, typename U>
const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
const T &key, /* note, not lifetimebound */
const U &default_value [[clang::lifetimebound]]);

Просто скажу, что мы в abseil облепились этими лайфтаймами и нашли сотню другую багов. Очень полезно даже для примитивных типов вроде unique_ptr::operator* и тд. Его можно ставить на аргументы функций и на функции класса пока.

Это достаточно полезно в любом месте, где у вас есть какой-нибудь контейнерный утиль, пользуйтесь.

Да, в Rust это встроено в язык, lifetimebound это упрощенный простой один lifetime 'a в Rust. За любой срач по Rust в коментах бан.

Привнести такой атрибут хотели давно в P0936 и очень долго пытаются починить всякие range based for.
👍66🔥15🤡15❤‍🔥53👏3🐳3👾3💩2😁1🤣1



group-telegram.com/experimentalchill/243
Create:
Last Update:

[[lifetimebound]]

В компиляторы C++ потихоньку приходят интересные фичи с memory safety, в этот раз поговорим о [[clang::lifetimebound]]. Он предназначен для того, чтобы показать, что жизнь возвращаемого объекта может зависеть от жизни аргумента

Я частенько видел код в духе

const std::string& s = StatusOrProtobuf()->field_value();

Где StatusOrProtobuf возвращает absl::StatusOr<Proto>, где мы знаем, что статус будет всего OkStatus.

И в этот момент я всегда задавался вопросом, а верно ли, что это просто неправильно? StatusOrProtobuf() будет же локальной переменной, в итоге мы берем ссылку на объект внутри локальной переменной, что вроде бы undefined behavior, так как локальная переменная разрушится.

Компиляторы и санитайзеры могут это не поймать так как примеры могут быть более интересными в духе


template<typename T, typename U>
const U &get_or_default(const std::map<T, U> &m,
const T &key,
const U &default_value);

В итоге если вернётся default value, то писать в духе

const std::string &val = get_or_default(m, "foo"s, "bar"s);

некорректно. В тестах можно забыть протестировать default_value, а в проде выстрелит.

В clang привнесли атрибут [[clang::lifetimebound]], который находит всякие такие баги на этапе компиляции. Можно писать


template<typename T, typename U>
const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
const T &key, /* note, not lifetimebound */
const U &default_value [[clang::lifetimebound]]);

Просто скажу, что мы в abseil облепились этими лайфтаймами и нашли сотню другую багов. Очень полезно даже для примитивных типов вроде unique_ptr::operator* и тд. Его можно ставить на аргументы функций и на функции класса пока.

Это достаточно полезно в любом месте, где у вас есть какой-нибудь контейнерный утиль, пользуйтесь.

Да, в Rust это встроено в язык, lifetimebound это упрощенный простой один lifetime 'a в Rust. За любой срач по Rust в коментах бан.

Привнести такой атрибут хотели давно в P0936 и очень долго пытаются починить всякие range based for.

BY Experimental chill


Warning: Undefined variable $i in /var/www/group-telegram/post.php on line 260

Share with your friend now:
group-telegram.com/experimentalchill/243

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

Telegram has gained a reputation as the “secure” communications app in the post-Soviet states, but whenever you make choices about your digital security, it’s important to start by asking yourself, “What exactly am I securing? And who am I securing it from?” These questions should inform your decisions about whether you are using the right tool or platform for your digital security needs. Telegram is certainly not the most secure messaging app on the market right now. Its security model requires users to place a great deal of trust in Telegram’s ability to protect user data. For some users, this may be good enough for now. For others, it may be wiser to move to a different platform for certain kinds of high-risk communications. As the war in Ukraine rages, the messaging app Telegram has emerged as the go-to place for unfiltered live war updates for both Ukrainian refugees and increasingly isolated Russians alike. The regulator took order for the search and seizure operation from Judge Purushottam B Jadhav, Sebi Special Judge / Additional Sessions Judge. Since January 2022, the SC has received a total of 47 complaints and enquiries on illegal investment schemes promoted through Telegram. These fraudulent schemes offer non-existent investment opportunities, promising very attractive and risk-free returns within a short span of time. They commonly offer unrealistic returns of as high as 1,000% within 24 hours or even within a few hours. Andrey, a Russian entrepreneur living in Brazil who, fearing retaliation, asked that NPR not use his last name, said Telegram has become one of the few places Russians can access independent news about the war.
from ye


Telegram Experimental chill
FROM American