Home > Software engineering >  Overwrite stack-allocated instance of a class
Overwrite stack-allocated instance of a class

Time:04-21

Consider the following code:

class A{
    
  public:
    A(){};
    
};

int main(){
    
    A a = A();
    std::cout << &a << std::endl;
    
    a = A();
    std::cout << &a << std::endl;

    return 0;
}

Both addresses are the same. The behavior that I expected was that the second call to A() would overwrite the variable a by creating a new instance of A, thereby changing the new address of a.

Why is this so? Is there a way to statically overwrite a that I am not aware of?

Thank you!

CodePudding user response:

Why is this so?

Within the scope of its lifetime, a variable is exactly one complete object (except in the case of recursion in which case there are multiple overlapping instances of the variable). a here is the same object from its declaration until the return of the function.

I expected was that the second call to A() would overwrite the variable a by creating a new instance of A,

It did that.

thereby changing the new address of a.

It didn't do that. The temporary object created by A() had a new address, but that temporary object was destroyed at the end of that full expression. a remained where it had been, and you invoked its assignment operator with the temporary object as the argument.

CodePudding user response:

The variable a is allocated on the stack. Its address is not going to change for the duration of the function. The first and the second instance of class A will be created in the space taken up but the variable.

  • Related