C++ Stack-allocated object assignment and destructor call
c++
Solution
Your instance f is being assigned a copy of Foo {"f2"}, it's not a new construction.
Add the following operator= override to illustrate what is actually happening.
Foo& Foo::operator=(const Foo& other) {
cout << "Foo::operator=(const Foo& other)" << endl;
m_name = other.m_name;
return *this;
}
Problem
I'm trying to understand what appears to be some weird behaviour when assigning a new value to an object allocated on stack (the destructor gets called twice for the same data set). I'll just start with the code snippet and its output: ``` class Foo { public: Foo(const string& name) : m_name(name) { log("constructor"); } ~Foo() { log("destructor"); } void hello() { log("hello"); } private: string m_name; void log(const string& msg) { cout << "Foo." << this << " [" << m_name << "] " << msg << endl; } }; int main() { { Foo f {"f1"}; f.hello(); f = Foo {"f2"}; f.hello(); } cout << "scope end" << endl; } ``` Output: ``` Foo.0x7fff58c66a58 [f1] constructor Foo.0x7fff58c66a58 [f1] hello Foo.0x7fff58c66a18 [f2] constructor Foo.0x7fff58c66a18 [f2] destructor Foo.0x7fff58c66a58 [f2] hello Foo.0x7fff58c66a58 [f2] destructor scope end ``` What I expected to happen: - 0x...58 gets created/initialised on stack - 0x...18 gets created/initialised on stack - Foo destructor gets called on 0x...58 (with f1 data) - Foo destructor gets called on 0x...18 (with f2 data) What actually happens: - 0x...58 gets created/initialised on stack - 0x...18 gets created/initialised on stack - data from 0x...18 (f2) gets copied onto 0x...58 - Foo destructor gets called on 0x...18 (with f2 data) - Foo destructor gets called on 0x...58 (also with f2 data) So in the end, Foo destructor gets called twice for the same data (f2). Clearly I'm missing something about how this works internally, so can someone please point me in the right direction?