It’s hard for me to understand why the following code does not create or destroy the two objects that I create, as I expected:
#include <iostream> class MyClass { int myVar; public: MyClass(int x) { myVar = x; std::cout << "constructing " << myVar << ", " << (long)this << std::endl; } ~MyClass() { std::cout << "destructing " << myVar << ", " << (long)this << std::endl; } }; int main(int argc, const char * argv[]) { MyClass a = MyClass(1); a = MyClass(2); return 0; }
I would think that inside main, I first create an object with a value of 1, and then create a new one with a value of 2. And each of the objects will be created and destroyed, so I expect to see the following output
constructing 1, 3456 constructing 2, 6789 destructing 1, 3456 destructing 2, 6789
However, I get the following:
constructing 1, 3456 constructing 2, 6789 destructing 2, 6789 <- note the "2" destructing 2, 3456
Update: I added the output of the object address (this) to better see which object is doing.
When I use the "new MyClass" instead, I do not come across this strange effect.
What causes this, and, understanding my goal, how to avoid such mistakes in the future?
While this example looks harmless, I ran into crashes of my code because I selected other objects in the constructor and freed them in the destructor. This led to the release of objects when the object was still in use.
Conclusion
Now that all my questions are answered, let me summarize:
- In the above example, I use "myVar", which does not even show the problem that made me address this issue. My apologies for this.
- The actual problem with the code was that I did not use a simple int var, but the array that I created with "new" in the destructor and freed up with deletion in the destructor. And with this, the array will be deleted twice, which will lead to incorrect data in my program.
- The fix is not to use a simple pointer to an array, but a reference count pointer, so that when it is copied by an assignment operator, it increases the refcount, thereby preventing it from being released prematurely.
- In general, the effect that I showed here is nothing dangerous - it does not cause anything, because I got the impression. The dangerous part was that I did not use ref counting ptrs.