C ++: does the compiler and the variable optimize; long away?

In C ++, the following statement is acceptable:

&Variable; 

IMO this makes no sense, so my question is, if you do, will it affect the compiled result in any way, or will the compiler optimize it?

Thanks!

+4
source share
6 answers

It is worth remembering that the & () operator can be overloaded for a variable type, have some side effects and optimize this instruction by changing the behavior of the program.

One example is the smart pointer used to manage objects other than C ++, _ com_ptr_t . It has an overloaded _com_ptr_t :: operator & () that checks if the pointer inside already contains some non-zero address. If it turns out that the stored address is not equal to zero, this means that the pointer is already bound to some object. If this happens, the operator _com_ptr_t :: operator & () disables the object - calls IUnknown :: Release () and sets the pointer to zero.

A side effect is needed here because this is a typical use:

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

CoCreateInstance () or other object search code has no idea about C ++ and _com_ptr_t, so it just rewrites the address passed into it. Therefore, _com_ptr_t :: operator & () must first free the object to which the pointer is bound, if any.

So for _com_ptr_t this statement is:

 &variable; 

will have the same effect as

 variable = 0; 

and its optimization will change the behavior of the program.

+6
source

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.

+10
source

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

+2
source

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

It can have side effects if the Variable class overrides the operator address (operator &).

+1
source

Yes, such a statement is likely to be optimized. This means taking a reference to a variable and throwing it away. Although when setting up "without optimization", your compiler may generate some code for this operator, it practically does not work, and this statement should go away with optimization.

+1
source

It seems you are referring to a local variable in the stack or case. The best way to find out what the compiler is doing at the moment is to view the disassembly view in Visual Studio.

Debugging a debugger (Visual Studio Orcas)

0
source

All Articles