Search code examples
c++pointersconstructorcopytemporary-objects

Is the address of a temporary object always the same as the address of the object it will be assigned to in C++?


In C++, suppose I have a C++ class called A, and inside it, I define a variable A* ptr;. In the constructor, there is an instruction ptr = this. Now, let's consider the following assignment initialization: A a = A(). My main question is whether a.ptr == &a is always true.

My primary concern is related to this assignment, which first creates a temporary object and then uses either the move constructor (possibly the copy constructor, I'm not entirely sure). I want to understand if the value of the ptr member in the temporary object is always the same as the address of the object it will be assigned to (i.e., whether the address of the temporary object is always the same as the address of a).

I have conducted experiments that seem to confirm this behavior, but I would like to know if this feature is guaranteed by the C++ standard.


Solution

  • Assignment happens when you have already constructed two objects and you want to overwrite one with the value of the other. If an object is being constructed right now, that's called initialization, and no assignment takes place to that object.

    A a;            // initialization
    A b(32);        // initialization
    A c = b;        // initialization
    b = c;          // assignment
    A d = A();      // initialization
    A e{42};        // initialization
    A *p = nullptr; // initialization (of a pointer)
    p = new A();    // assignment of p, initialization of the new A object
    *p = d;         // assignment of the A object
    

    In your case the line A a = A(); performs initialization since a is being constructed right now. Since C++17, the initialization is performed in-place whenever the expression is a prvalue, like your A(). No copy is being performed here. The temporary object created by A() is never materialized in memory elsewhere and then copied, it's directly created in the right spot.

    Effectively, you can pretend that no temporary object exists in this case. You can equivalently write A a; and obtain the same effect.