auto_ptr,该如何解决

auto_ptrauto_ptrhaveanunusualcharacteristic:copyingthem(viacopyconstructororcopyassignment)setsthem

auto_ptr
auto_ptr   have   an   unusual   characteristic:   copying   them(via   copy   constructor   or   copy   assignment)sets   them   to   null.

why   the   program   run   correctly:
#include   <stdAfx.h>
#include   <iostream>
#include   <memory>
using   namespace   std;

class   A
{
public:
A(int   a):m_iData(a){};
void   print(){cout < <this-> m_iData < <endl;}
private:
int   m_iData;
};

void   smart()
{
auto_ptr <A>   m_pSmartA(new   A(2));
//m_pSmartA-> print();
auto_ptr <A>   m_pSmartA1(m_pSmartA);
m_pSmartA1-> print();
m_pSmartA-> print();
};

void   main()
{
smart();
}

the   result:
2
2
i   was   puzzled   how   the   result   got.
can   u   tell   me   why?   thank   u   first.

[解决办法]
auto_ptr <A> m_pSmartA1(m_pSmartA);
此时m_pSmartA指向null了,释放对象A(2)的所有权
[解决办法]
new了一個A的object,用pSmartA和pSmartA1分別指向那個object
[解决办法]
偶用VC2003编译运行楼主的程度,引发严重的运行时错误。- -b
[解决办法]
“程序”,打错了。
[解决办法]
用g++3.4.4也一样。- -b
楼主用的是啥编译器啊?竟能正常运行?
[解决办法]
你打开vc6的memory这个头文件,看一下它的实现就知道原因了。
[解决办法]
auto_ptr 的特征是所有权转移,也就是任何时候只会有一个auto_ptr 对象指向你的对象.

void smart()
{
auto_ptr <A> m_pSmartA(new A(2));
m_pSmartA-> print();
auto_ptr <A> m_pSmartA1(m_pSmartA);//这里,用pSmartA构造pSmartA1时,发生了所有权转移.m_pSmartA不再指向(new A(2)),而是由m_pSmartA1指向(new A(2))
m_pSmartA1-> print();
m_pSmartA-> print();//所以这里是用一个无效的对象在调用,相当C中NULL指针调用.
};
[解决办法]
要么学习标准C++,要么用VC6,两者是不可兼得的,嘿嘿。

当然,这不能怪微软,因为VC6发布的时候,C++标准化工作还没完成。而C++标准化工作完成之后,人家微软还是出了更好的新版本的,比如VC7.0,2003,2005等。
[解决办法]
对于0指针进行解引用,行为属未定义
对于0指针进行delete,是安全的行为