Telegram Group & Telegram Channel
C++: зачем [[nodiscard]] на bool — и почему это важно

Когда функция возвращает bool, часто возникает соблазн проигнорировать результат:


is_valid(user); // ничего не делает!


А теперь представьте, что is_valid() проверяет критическое условие. Без проверки — баг, возможно даже security-уязвимость.

Чтобы защититься от такого, с C++17 есть [[nodiscard]]:


[[nodiscard]] bool is_valid(const User& user);


Теперь, если результат проигнорировать — компилятор предупредит:


warning: ignoring return value of 'is_valid', declared with attribute 'nodiscard'


Можно ещё улучшить читаемость — использовать [[nodiscard("Must check if user is valid")]], чтобы компилятор написал пояснение в варнинге (начиная с C++20).

🔥 Лайфхак: ставьте [[nodiscard]] на все функции, где игнорирование результата — это почти всегда ошибка. Особенно на:

* проверки (is_...)
* операции с возможным фейлом (try_..., parse_...)
* RAII-объекты с флагами состояния

Не ленитесь — [[nodiscard]] спасает от тонких багов и делает код надёжнее.

➡️ @cpp_geek



tg-me.com/cpp_geek/315
Create:
Last Update:

C++: зачем [[nodiscard]] на bool — и почему это важно

Когда функция возвращает bool, часто возникает соблазн проигнорировать результат:


is_valid(user); // ничего не делает!


А теперь представьте, что is_valid() проверяет критическое условие. Без проверки — баг, возможно даже security-уязвимость.

Чтобы защититься от такого, с C++17 есть [[nodiscard]]:


[[nodiscard]] bool is_valid(const User& user);


Теперь, если результат проигнорировать — компилятор предупредит:


warning: ignoring return value of 'is_valid', declared with attribute 'nodiscard'


Можно ещё улучшить читаемость — использовать [[nodiscard("Must check if user is valid")]], чтобы компилятор написал пояснение в варнинге (начиная с C++20).

🔥 Лайфхак: ставьте [[nodiscard]] на все функции, где игнорирование результата — это почти всегда ошибка. Особенно на:

* проверки (is_...)
* операции с возможным фейлом (try_..., parse_...)
* RAII-объекты с флагами состояния

Не ленитесь — [[nodiscard]] спасает от тонких багов и делает код надёжнее.

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/315

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

At a time when the Indian stock market is peaking and has rallied immensely compared to global markets, there are companies that have not performed in the last 10 years. These are definitely a minor portion of the market considering there are hundreds of stocks that have turned multibagger since 2020. What went wrong with these stocks? Reasons vary from corporate governance, sectoral weakness, company specific and so on. But the more important question is, are these stocks worth buying?

Telegram Auto-Delete Messages in Any Chat

Some messages aren’t supposed to last forever. There are some Telegram groups and conversations where it’s best if messages are automatically deleted in a day or a week. Here’s how to auto-delete messages in any Telegram chat. You can enable the auto-delete feature on a per-chat basis. It works for both one-on-one conversations and group chats. Previously, you needed to use the Secret Chat feature to automatically delete messages after a set time. At the time of writing, you can choose to automatically delete messages after a day or a week. Telegram starts the timer once they are sent, not after they are read. This won’t affect the messages that were sent before enabling the feature.

telegram from sg


Telegram C++ geek
FROM USA