Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 761
clamp Avatar asked Dec 01 '22 12:12

clamp


2 Answers

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.

like image 94
Alex B Avatar answered Dec 04 '22 09:12

Alex B


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.

like image 24
sharptooth Avatar answered Dec 04 '22 08:12

sharptooth