Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to specify [[nodiscard]] before C++17

Tags:

c++

nodiscard

I need the semantics of the [[nodiscard]] attribute in a non-C++17 codebase. I guess there are compiler dependent ways of achieving this before C++17. Does anyone know these? I am interested in the ones for clang,gcc, and MSVC.

like image 747
gexicide Avatar asked Jul 19 '17 12:07

gexicide


People also ask

Should I use [[ Nodiscard ]]?

It is never necessary to add the [[nodiscard]] attribute. From cppreference: If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.

What means [[ Nodiscard ]]?

C++17 introduces the [[nodiscard]] attribute, which allows programmers to mark functions in a way that the compiler produces a warning if the returned object is discarded by a caller; the same attribute can be added to an entire class type.

What does no discard mean?

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.

What is attribute in C Plus Plus?

Attributes are one of the key features of modern C++ which allows the programmer to specify additional information to the compiler to enforce constraints(conditions), optimise certain pieces of code or do some specific code generation.


1 Answers

  • GCC/Clang: __attribute__((warn_unused_result))
  • MSVC: _Check_return_ for _MSC_VER >= 1700 (Visual Studio 2012)
like image 72
Nikolai Shalakin Avatar answered Oct 06 '22 22:10

Nikolai Shalakin