Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can 'unused variable' optimization prevent an exception?

Tags:

c++

I have the following code:

void check_portvalue(std::string_view value)
{
    [[maybe_unused]] port_t test {value};
}

The object test remains unused, but creation serves as a check, because the constructor can throw. The [[maybe_unused]] attribute suppresses the compiler warning.

But since the compiler detects that this is unused, could it optimize out the entire statement and thus prevent the exception from being thrown ?

like image 663
Tootsie Avatar asked Oct 23 '25 15:10

Tootsie


1 Answers

Optimizer has to follow the as-if rule (i.e cannot change "observable behaviors")

The only exception to the as-if rule are:

  • Copy elision
  • the compiler may remove calls to the replaceable allocation functions.

Your code doesn't fall into those categories.

like image 149
Jarod42 Avatar answered Oct 25 '25 04:10

Jarod42