Skip to content

Latest commit

 

History

History
261 lines (222 loc) · 3.03 KB

attributes.md

File metadata and controls

261 lines (222 loc) · 3.03 KB

some new [[attributes]]

[[fallthrough]]

C++14 C++17
switch (device.status())
{
case sleep:
   device.wake();
   // fall thru
case ready:
   device.run();
   break;
case bad:
   handle_error();
   break;
}
switch (device.status())
{
case sleep:
   device.wake();
   [[fallthrough]];
case ready:
   device.run();
   break;
case bad:
   handle_error();
   break;
}
Compiler Compiler
warning: case statement without break

[[nodiscard]]

On functions:

C++14 C++17
struct SomeInts
{
   bool empty();
   void push_back(int);
   //etc
};

void random_fill(SomeInts & container,
      int min, int max, int count)
{
   container.empty(); // empty it first
   for (int num : gen_rand(min, max, count))
      container.push_back(num);
}
struct SomeInts
{
   [[nodiscard]] bool empty();
   void push_back(int);
   //etc
};

void random_fill(SomeInts & container,
      int min, int max, int count)
{
   container.empty(); // empty it first
   for (int num : gen_rand(min, max, count))
      container.push_back(num);
}
Compiler C++17 Compiler
warning: ignoring return value of 'bool empty()'

On classes or structs:

C++14 C++17
struct MyError {
  std::string message;
  int code;
};

MyError divide(int a, int b) {
  if (b == 0) {
    return {"Division by zero", -1};
  }

  std::cout << (a / b) << '\n';

  return {};
}

divide(1, 2);
struct [[nodiscard]] MyError {
  std::string message;
  int code;
};

MyError divide(int a, int b) {
  if (b == 0) {
    return {"Division by zero", -1};
  }

   std::cout << (a / b) << '\n';

  return {};
}

divide(1, 2);
Compiler C++17 Compiler
warning: ignoring return value of function declared with 'nodiscard' attribute

Advice: use [[nodiscard]] sparingly. ie only when there really is no reason to ignore the value.

[[maybe_unused]]

C++14 C++17
   bool res = step1();
   assert(res);
   step2();
   etc();
   [[maybe_unused]] bool res = step1();
   assert(res);
   step2();
   etc();
Compiler C++17 Compiler
warning: unused variable 'res'
C++17
   [[maybe_unused]] void f()
   {
      /*...*/
   }
   int main()
   {
   }