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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With