1.auto_ptr转移所有权的行为
#include<iostream>
#include<memory>using namespace std;
template <class T>
ostream& operator<< (ostream &strm, const auto_ptr<T>& p)//因为output的第二个参数地const引用,所有没有发生拥有权转移。
{
if (p.get() == NULL)
strm << "NULL";
else
{
strm << *p;
}
return strm;
}
int main()
{
auto_ptr<int> p(new int(42));
//auto_ptr<int> p = new int(42);
//不通过编译的原因是 根据一般指针生成一个auto_ptr的那个构造函数 被声明为explicit
auto_ptr<int> q;
cout << "after initialization:" << endl;
cout << "p:" << p << endl;
cout << "q:" << q << endl;
q = p;
cout << "after assigning auto pointer:" << endl;
cout << "p:" <<p <<endl;
cout << "q:" <<q<< endl;
*q += 13;
p = q;
cout << "after change ressignment:" << endl;
cout << "p:" << p << endl;
cout << "q:" << q << endl;
getchar();
getchar();
}
2.const auto_ptr的特性
#include<iostream>
#include<memory>
using namespace std;
template<class T>
ostream& operator<<(ostream& strm, const auto_ptr<T>& p){
if (p.get() == NULL)
strm << "NULL";
else
strm << *p;
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 initialiaing :" << endl;
cout << "p:" << p << endl;
cout << "q:" << q << endl;
cout << "r:" << r << endl;
*q = *p;
//*r = *p; //这句代码会在运行期报错undefine behaviior
*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 = q; ERROR AT COMPILE TIME
getchar();
getchar();
}