0

代码片段(普通指针)

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

[Output: 100]

代码片段(自动指针)

情况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)

案例二:

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

[Output: 100]

有人可以告诉为什么它对案例 1 不起作用吗?

4

2 回答 2

2

您试图将auto_ptr 绑定到堆栈分配的变量。

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

永远不要尝试这样做 - 只绑定auto_ptr到分配有new. 否则 auto_ptr 将尝试delete堆栈分配的变量,这是未定义的行为。

于 2010-04-23T06:29:44.850 回答
2

情况 1无法编译,因为您根本无法将普通指针分配给auto_ptr. 如果要更改auto_ptr正在照顾的指针,可以使用 reset 方法:

pi.reset(&i);

现在pi将删除它之前存储的指针。

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

于 2010-04-23T11:07:12.180 回答