最近看侯捷翻译的《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
赋值之后,原指针不是应该为空吗?
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
赋值之后,原指针不是应该为空吗?
经过验证,是由于VC6.0的实现问题,VS2010没问题。