//展示const auto_ptr的特性
#include <iostream>
#include <memory>
using namespace std;
/* define output operator for auto_ptr
* print object value or NULL
*/
template <class T>
ostream& operator<< (ostream& strm, const auto_ptr<T>& p)
{
// does p own an object ?
if (p.get() == NULL)
{
strm << "NULL"; // NO: print NULL
}
else
{
strm << *p; // YES: print the object
}
return strm;
}
int main()
{
const auto_ptr<int> p(new int(42));
const auto_ptr<int> q(new int (0));
const auto_ptr<int> r;
cout << "after initialization:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
cout << " r: " << r << endl;
*q = *p;
//*r = *p; // ERROR: undefined behavior 對(duì)于一個(gè)“未指向任何對(duì)象”的auto_ptr進(jìn)行提領(lǐng)(dereference)操作,C++標(biāo)準(zhǔn)規(guī)格,
//這會(huì)導(dǎo)致未定義行為,比較如說(shuō)導(dǎo)致程序的崩潰。
*p = -77;
cout << "after assigning values:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
cout << " r: " << r << endl;
//q = p; // ERROR at compile time
//r = p; // ERROR at compile time
}
輸出結(jié)果:
after initialization:
p: 42
q: 0
r: NULL
after assigning values:
p: -77
q: 42
r: NULL
請(qǐng)按任意鍵繼續(xù). . .