Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 contracts and unused variables

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?

like image 735
KyleKnoepfel Avatar asked Jul 09 '19 16:07

KyleKnoepfel


1 Answers

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.

like image 58
Davis Herring Avatar answered Nov 11 '22 08:11

Davis Herring