0

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?

Akaanthan Ccoder
  • 2,159
  • 5
  • 21
  • 37

2 Answers2

2

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
  • 167,383
  • 100
  • 513
  • 979
  • Ok. I changed as below, it worked. { int *i = new int; *i = 90; pi = &i; } One interesting point. The moment I copied 'i' to 'pi', then 'i' became NULL. (I think that is how auto_ptr designed to work) – Akaanthan Ccoder Apr 23 '10 at 07:15
2

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
  • 8,564
  • 2
  • 26
  • 15
  • Thanks for your view. When I assigned like pi = &i, during debugging, while dereferencing (*), it raised an exception. When I assigned like pi.reset(&i), it succeeded while dereferencing , but when the program came out of scope, it crashed. I can understand this because, auto_ptr has tried to delete the stack allocated memory when method goes out of scope. – Akaanthan Ccoder Apr 23 '10 at 12:22
  • 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 Apr 23 '10 at 12:42