C++智能指針與返回局部指針測試

智能指針:對new對象進行智能的管理,跳出相關作用域會自動刪除。 不需要再調用delete。對象刪除會自動調用析構函數。

這裏只記錄:unique_ptr 與shared_ptr      auto_ptr已經被unque_ptr替換  weak_ptr不是特別常用。
unique_ptr 是唯一的智能指針管理,同時只有一個記錄,不可直接等於,通過std::move轉換給另一個智能指針,當前指針被置爲NULL。這個智能指針比auto_ptr安全的多,
unique_ptr會智能判斷,賦值,假如這個指針會在內存中停留一段時間,不會讓直接賦值,需要通過std::move轉換給另一個智能指針。 如果是函數內的局部變量,可以直接賦值給unique_ptr智能指針(例2)。
例1:
unique_ptr<Base> xx(newBase("b"));
   
   
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);//智能指針交換值
   //cout << xx3.get() << endl;


例2 返回局部函數地址的討論,返回局部指針:
unique_ptr<Base> test()
{
   
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;
}

intmain(intargc,constchar * argv[]) {
      unique_ptr<Base> xx4 = test();  //這種調用就可以直接賦值
   
cout << "unique_ptr<Base> xx4 " << xx4.get() <<endl;
   
   
Base* xx5 = test1();
   
cout << "xx5 = " << xx5 << endl;
   
char* xx6 =test2();
   
cout << &xx6 << endl;
   deletexx5; //主動調用delete 智能指針不需要主動調用delete
}


例3 在類中的寫法:
class Derived : public Base
{
public:
    Derived(
string xx):Base(xx)
    {
        cout << "Derived 構造" << endl;
         _other = unique_ptr<Other>(new Other());
    }
   
    Derived() {
       
cout << "Derived 構造" << endl;
    }
   
    ~Derived() {
       
cout << "Derived 析構函數" << endl;
    }
private:
   
unique_ptr<Other> _other;
};

int main(int argc, const char * argv[]) {
      unique_ptr<Base> xx2(new Derived("a"));
}



shared_ptr  引用計數方式管理內存的智能指針,每次賦值的時候引用計數會+1, 對象.reset(); 引用計數會 -1。引用計數爲0的時候,delete掉指針對象,並調用析構函數。
   shared_ptr<Base> xx(newBase("b"));
   cout<< xx.use_count() <<endl;
   
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的時候,調用創建對象的析構函數
   cout<< xx.use_count() <<endl;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章