Skip to content

No discard

C++17 introduced [[nodiscard]] attribute. When you declare a function [[nodiscard]], you indicate that its return value should not be ignored. This can help prevent bugs related to:

  • Memory leak, in case the function returns a pointer to unmanaged memory
  • Performance, in case the discarded value is costly to construct
  • Security, in case the return value indicates an error condition that needs to be taken into account

Example:

cpp
[[nodiscard]] int Compute();
[[maybe_unused]] auto t = Compute();

Maybe unused

Here's an example where [[maybe_unused]] is commonly accepted:

c
#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
   std::vector<int> v {0, 1, 2, 3 };

   std::cout << std::count_if (v.begin (), v.end (), [] (int i) {return (i & 1);}) << "\n";
   std::cout << std::count_if (v.begin (), v.end (), [] ([[maybe_unused]] int i) {return true;}) << "\n"; // Compiles without a warning
   std::cout << std::count_if (v.begin (), v.end (), [] (int i) {return false;}) << "\n"; // Produces a warning
}

References