开发者

Normal pointer vs Auto pointer (std::auto_ptr)

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;
in开发者_运维百科t k = *pi + 10;
cout<<k<<endl;

[Output: 100]

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


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜