代码段(普通指针)
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)
情况2:
std::auto_ptr<int> pi(new int);
int i = 90;
*pi = 90;
int k = *pi + 10;
cout<<k<<endl;
[Output: 100]
有人可以告诉我为什么它在案例1中不起作用吗?
最佳答案
您试图将auto_pt
r绑定到堆栈分配的变量。
std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;
从不尝试执行此操作-仅将
auto_ptr
绑定到使用new
分配的变量。否则,auto_ptr将尝试delete
堆栈分配的变量,这是未定义的行为。关于c++ - 普通指针与自动指针(std::auto_ptr),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2696635/