简体   繁体   中英

Can the optimizer elide variables declared in a namespace

I am looking at some legacy code and it performs something akin to the following:

namespace MyNamespace
{
   const bool myVariable = f::y();
}

Where f::y() has the side effect of registering something in a singleton owned map.

My question is, if MyNamespace::myVariable is not accessed directly, does the standard allow the optimizer to eliminate it entirely? This would have to be a link time optimization (I think) and I'm not sure how much the standard has to say about such things. I haven't been able to find the proper reference on my own.

The compiler is presently a C++03 conforming compiler but will soon be migrated to a C++14 compiler.

If f::y() has an observable side effect, then the compiler is not allowed to optimize away that call. The only instance I'm aware of, where the compiler is actually allowed to do optimizations that change the program's behavior is when an object is copyied (copy-elision).

But if myVariable isn't accessed anywhere*) in your translation unit (as explained by jonathan), then the compiler doesn't actually have to reserve any space for the variable.

So in short: It can optimize away the variable, but most likely not the function call.

*) I believe the term to look for is ODR-Used

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM