关于智能指针auto_ptr
最近看侯捷翻译的《C++ 标准程序库》有一个auto_ptr的示例
template <class T>
ostream& operator<<(ostream &out, const auto_ptr<T>& p)
{
if (p.get() == NULL) {
out << "NULL";
}else{
out << *p;
}
return out;
}
int main()
{
auto_ptr<int> p(new int(42));
auto_ptr<int> q;
cout << "after initialization" << endl;
cout << "p: " << p << endl;
cout << "q: " << q << endl;
q = p;
cout << "after assigning auto_ptr pointers" << endl;
cout << "p: " << p << endl;
cout << "q: " << q << endl;
*q += 13;
p = q;
cout << "after change and reassignment" << endl;
cout << "p: " << p << endl;
cout << "q: " << q << endl;
return 0;
}
用VC++ 6.0编译的,为什么结果是
after initialization
p: 42
q: NULL
after assigning auto_ptr pointers
p: 42
q: 42
after change and reassignment
p: 55
q: 55
Press any key to continue
不是应该是:
after initialization
p: 42
q: NULL
after assigning auto_ptr pointers
p: NULL
q: 42
after change and reassignment
p: 55
q: NULL
赋值之后,原指针不是应该为空吗?
[解决办法]
在 vc2010 里:
after initialization
p: 42
q: NULL
after assigning auto_ptr pointers
p: NULL
q: 42
after change and reassignment
p: 55
q: NULL
vc 6 都成古董了
[解决办法]
请参考:
使用auto_ptr需要注意的事项
[解决办法]
VC6.0是C++标准出来前的东西了,对标准支持不好