简体   繁体   中英

C++ : Will compiler optimize &Variable; away?

In C++ a statement like this is valid:

&Variable;

IMO it doesn't make any sense, so my question is, if you do this, will it affect the compiled result in any way, or will the compiler optimize it away?

Thanks!

Consider this snippet:

#include <iostream>
class A {
public:
    A* operator &() {
        std::cout << "aaa" << std::endl;
        return this;
    }
};

int main() {
    A a;
    &a;
    return 0;
};

In this case, "&a;" will generate code.

It's worth remembering that operator&() might be overloaded for the variable type, have some side effects and optimizing away such statement would change program behaviour.

One example is a smart pointer used for controlling the non-C++ objects - _com_ptr_t . It has an overloaded _com_ptr_t::operator&() which checks whether the pointer inside already stores some non-null address. If it turns out that the stored address is non-null it means that the pointer is already attached to some object. If that happens the _com_ptr_t::operator&() disconnects the object - calls IUnknown::Release() and sets the pointer to null.

The side effect here is necessary because the typical usage is this:

_com_ptr_t<Interface> pointer;
// some other code could be here
CoCreateInstance( ..., &pointer, ...);// many irrelevant parameters here

CoCreateInstance() or other object retrieval code has no idea about C++ and _com_ptr_t so it simply overwrites the address passed into it. That's why the _com_ptr_t::operator&() must first release the object the pointer is attached to if any.

So for _com_ptr_t this statement:

&variable;

will have the same effect as

variable = 0;

and optimizing it away would change program behaviour.

That depends entirely on the compiler and the compilation options you use. There is nothing in the C++ Standard to prevent a compiler from generating code for such a statement.

Do you want to remove it, but are worried that you may alter the behavior of the program?

It could have side-effects if Variable's class overrides the address-of-operator (operator&).

Yes, such statement is likely to be optimized. It means to take a reference to variable and throw it away. While at 'no optimization' setting your compiler may generate some code for this statement, it is essentially no-op and with optimization this statement should go away.

It seems you take a reference to a local variable on stack or register. The best way to find out what the compiler does at the moment is to view the Disassembly view in Visual Studio.

Disassembly view in Debugger (Visual Studio Orcas)

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