unique_ptr<Base> xx2(newDerived("a"));
//xx2 = move(xx); // xx2先被析構然後xx被賦值給xx2 xx的指針置爲null 不能相互轉換的類不同通過move賦值
//xx->printxx(); //這樣來調用類方法 因爲是指針
//xx.get(); //這樣來調用智能指針的庫方法,獲取指針的地址。
cout << xx.get() <<endl;
cout << xx2.get() <<endl;
//unique_ptr<Base> xx3 = xx2; //直接賦值不行 必須要用std::move
unique_ptr<Base> xx3 =move(xx2);
cout << "xx2 = " << xx2.get() <<endl;
xx3.reset();//主動釋放並調用析構函數 release指針制空不會調用析構函數 智能指針一般不需要主動釋放
cout << "xx3 = " << xx3.get() <<endl;
xx3.swap(xx);//智能指針交換值
{
unique_ptr<Base> xx(newBase("unique_ptr<Base>"));//函數內的局部返回智能指針是兼容的
cout << "unique_ptr<Base> test() " << xx.get() <<endl;
returnxx;
}
Base* test1()
{
Base* base = new Base("new Base");
cout << "base = " << base <<endl;
returnbase;
}
char* test2()
{
charxx[] ="x";
cout << &xx << endl;
returnxx;
cout << "unique_ptr<Base> xx4 " << xx4.get() <<endl;
Base* xx5 = test1();
cout << "xx5 = " << xx5 << endl;
char* xx6 =test2();
cout << &xx6 << endl;
{
public:
Derived(string xx):Base(xx)
{
Derived() {
cout << "Derived 構造" << endl;
}
~Derived() {
cout << "Derived 析構函數" << endl;
}
private:
unique_ptr<Other> _other;
shared_ptr<Base> xx2 = xx;
cout << "xx = " << xx.get() <<endl;
cout << "xx2 = " << xx2.get() <<endl;
cout << xx.use_count() <<endl;
xx2.reset(); //銷燬當前對象引用計數減1
cout << xx2.get() <<endl; //指針置爲null
cout << xx.use_count() <<endl;
xx.reset(); //引用計數爲0的時候,調用創建對象的析構函數