views:

211

answers:

2

Code snippet (normal pointer)

int *pi = new int;
int i = 90;
pi = &i;
int k = *pi + 10;
cout<<k<<endl; 
delete pi;

[Output: 100]

Code snippet (auto pointer)

Case 1:

std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;
int k = *pi + 10; //Throws unhandled exception error at this point while debugging.
cout<<k<<endl;
//delete pi; (It deletes by itself when goes out of scope. So explicit 'delete' call not required)

Case 2:

std::auto_ptr<int> pi(new int);
int i = 90;
*pi = 90;
int k = *pi + 10;
cout<<k<<endl;

[Output: 100]

Can someone please tell why it failed to work for case 1?

+2  A: 

You tried to bind auto_ptr to a stack allocated variable.

std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;

never try to do that - only bind auto_ptr to variables allocated with new. Otherwise auto_ptr will try to delete a stack allocated variable and that's undefined behavior.

sharptooth
Ok. I changed as below, it worked. { int *i = new int; *i = 90; pi = }One interesting point. The moment I copied 'i' to 'pi', then 'i' became NULL. (I think that is how auto_ptr designed to work)
AKN
+2  A: 

Case 1 fails to compile, because you simply can't assign a plain pointer to an auto_ptr. If you want to change the pointer that the auto_ptr is looking after, you can use the reset method:

pi.reset(&i);

Now pi will delete the pointer it was storing earlier.

However, here you'd be storing the address of a stack allocated variable which must not be deleted. The purpose of std::auto_ptr is to manage a dynamically allocated variable.


What you are observing with VC++ 2005 appears to be a bug in the implementation of a feature (ability to assign pointers to std::auto_ptr) which is apparently unspecified in the standard (whether it should or shouldn't compile).

In the next standard std::auto_ptr will be deprecated anyway, so you might rather experiment with saner smart pointers (boost::scoped_ptr, boost::shared_ptr).

visitor
AKN
It appears you have stumbled upon a bug in the library implementation: http://connect.microsoft.com/VisualStudio/feedback/details/98871/memory-corruption-in-auto-ptr-operator-auto-ptr-ref. Just remember that assigning a pointer to `auto_ptr` is not portable (I would have thought it was the intention of the standard that this shouldn't compile, but perhaps it is unspecified).
visitor