Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::move not [[nodiscard]] in C++20?

I've recently read about [[nodiscard]] in C++17, and as far as I understand it's a new feature (design by contract?) which forces you to use the return value. This makes sense for controversial functions like std::launder (nodiscard since C++20), but I wonder why std::move isn't defined like so in C++17/20. Do you know a good reason or is it because C++20 isn't finalised yet?

like image 425
bbalchev Avatar asked Apr 20 '19 10:04

bbalchev


People also ask

What is[[ nodiscard]] in c++?

The [[nodiscard]] attribute can be used to indicate that the return value of a function shouldn't be ignored when you do a function call. If the return value is ignored, the compiler should give a warning on this.

Should you use Nodiscard?

Yes, using [[nodiscard]] is a good practice when discarding the result is likely a bug.


Video Answer


1 Answers

The MSVC standard library team went ahead and added several thousand instances of [[nodiscard]] since VS 2017 15.6, and have reported wild success with it (both in terms of finding lots of bugs and generating no user complaints). The criteria they described were approximately:

  1. Pure observers, e.g. vector::size(), vector::empty, and even std::count_if()
  2. Things that acquire raw resources, e.g. allocate()
  3. Functions where discarding the return value is extremely likely to lead to incorrect code, e.g. std::remove()

MSVC does mark both std::move() and std::forward() as [[nodiscard]] following these criteria.

While it's not officially annotated as such in the standard, it seems to provide clear user benefit and it's more a question of crafting such a paper to mark all the right things [[nodiscard]] (again, several thousand instances from MSVC) and apply them -- it's not complex work per se, but the volume is large. In the meantime, maybe prod your favorite standard library vendor and ask them to [[nodiscard]] lots of stuff?

like image 175
Barry Avatar answered Sep 19 '22 17:09

Barry