3

If a variable is only used in an assert, then compilers usually produce a warning when the program is compiled in release mode (i.e. without debug flags). This question suggests ways to disable these particular warnings. Among the answers, the C++17 attribute maybe_unused is suggested. However, these answers have not really been discussed.

Are there any drawbacks to using [[maybe_unused]] in situations like this one

[[maybe_unused]] const auto i = get_i();
assert(i == 5);

in order to silence the warning about i being unused in a release build?

user2296653
  • 1,151
  • 1
  • 8
  • 17

1 Answers1

0

The problem with such a suggestion is that they might cause some overhead without a warning, especially after some refactoring.

Only the content/expression inside of an assert is usually completely removed in release builds.

If you want to use variables in your assert, you can use lambdas. See this example:

#include <cassert>

auto get_i(){
    return 5;
}

int main(){
    /* BAD
    [[maybe_unused]] const auto i = get_i();
    assert(i == 5);
    */
    
    assert([&](){
        const auto i = get_i();
        return i == 5;
    }());
}
Bernd
  • 2,113
  • 8
  • 22