11

Apologies if this has been covered elsewhere. One of my frustrations has been that whenever I'm trying to check a post-condition of calling a function, I often must decorate the return variable as unused to avoid compiler warnings:

auto const count [[maybe_unused]] = some_map.erase(some_key);
assert(count == 1);

The reason for the attribute is clear--assert is a preprocessor macro that either expands to a no-op if NDEBUG is set, or actually evaluates the expression if NDEBUG is not set. In the former case, count is technically not used, hence the compiler warning.

With the introduction of contracts in C++20, will the count variable still be considered unused? In other words, will I be able to do:

auto const count = some_map.erase(some_key); // no attribute
[[assert: count == 1]];

or will I have to do something ugly like:

auto const count [[maybe_unused]] = some_map.erase(some_key);
[[assert: count == 1]];

Or is this implementation-defined behavior?

Barry
  • 247,587
  • 26
  • 487
  • 819
KyleKnoepfel
  • 1,240
  • 6
  • 23
  • 4
    [gcc doesn't warn here](https://godbolt.org/z/87Wplc). – Barry Jul 09 '19 at 16:15
  • @Barry Thanks. Is there anywhere in the current C++ standard, or in the contracts proposal(s) that addresses when a variable is considered unused? – KyleKnoepfel Jul 09 '19 at 16:21
  • Pretty sure no to the former. And there's a million contracts-related proposals, so... shrug. – Barry Jul 09 '19 at 16:23
  • 4
    Warnings are entirely QoI. That said, I don't see how any high-quality implementations would warn here. – T.C. Jul 09 '19 at 17:45
  • Note that contracts got pulled from C++20 for want of agreement on what options and settings to supply. A similar feature is likely to reappear later. – Davis Herring Aug 06 '19 at 13:05

1 Answers1

4

The standard doesn’t define used at all. That said, a contract assertion is morally equivalent to

if(__check_contract<level>())
  if(!condition) __handle_violation(…);

and compilers generally do not warn even if a condition for a usage is a literal false (because of generated code, among other reasons). So you should be fine.

Davis Herring
  • 24,173
  • 3
  • 25
  • 55