Please have a look at the code below. Is this a smart pointer?
If so, why the first object, p1, is dangling at the end of the code? (That is p2 is deleted by the destructor but p1 remains, why?)
@Thomas1965: Yes, I agree.
And to me it's not a smart pointer enough, because we need to add a block for every pointer we create.
My compiler is MS VS 2015. And I ran the code through "Run To Cursor" mode.
Thanks to all.
Best way to find out if you're destructor is being called for both objects?
Do this:
Add a cout statement saying "Destructing auto_ptr" inside your destructor. Next, run your program from the COMMAND PROMPT in windows. This console won't close and you'll get to see the destructor output. You should see two destructor lines, indicating that it was called twice - once for each auto_ptr.
I didn't say that it didn't work. I meant that when it went out of scope there that the console was closed already. That's the reason why I added the additional scope to see a result. When using a logfile it clearly show that both destructors were called.
Sorry if I was not clear enough, but English is not my native language.
The fundamental concept of C++ is that the destructor is called when an object falls out of the scope where the constructor is called.
That means when an exception arise during or before the constructor is called the destructor isn't called either. Thus it is possible due to an exception that the destructor is not called.
You guys, are right. I added the system ("pause"); inside the destructor's body and it showed that the destructor was called for both pointers. Even when I created another object, for this one too, the destructor was called. And also there is no need to add any redundant blocks.
Apparently we cannot only rely on the "Run To Cursor" feature for seeing what is happening. Thanks.