C++ stack based constructor not working as expected
(Sorry, I do not even know how to describe the issue in the title as I'm
not sure about the terms, please fix if you know.)
I have trouble understanding why the following code doesn't construct and
destruct the two objects I create the way I'd expect:
#include <iostream>
class MyClass {
int myVar;
public:
MyClass(int x) {
myVar = x;
std::cout << "constructing " << myVar << std::endl;
}
~MyClass() {
std::cout << "destructing " << myVar << std::endl;
}
};
int main(int argc, const char * argv[])
{
MyClass a = MyClass(1);
a = MyClass(2);
return 0;
}
I'd think that inside main I first create an object with the value 1, then
create a new one with value 2. And each of the objects gets constructed
and destructed, so that I'd expect to see the following output:
constructing 1
constructing 2
destructing 1
destructing 2
Howver, I get this:
constructing 1
constructing 2
destructing 2 <- note this
destructing 2
When I use "new MyClass" instead, I do not run into this weird effect.
What is causing this, and, understanding my goal, what is the right way to
fix this, and avoid similar mistakes in the future? I mean, I've worked
with other OO languages and there I never ran into this (though they do
not have this odd "feature" that I can create object both on the heap with
"new" and on the stack without "new"), so I'm somewhat afraid that similar
bugs lurk in other places of my code as well.
No comments:
Post a Comment