C++智能指针与返回局部指针

来源:互联网 发布:java定时器讲解 编辑:程序博客网 时间:2024/06/06 20:18



智能指针:对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(){    char xx[] ="x";    cout << &xx << endl;    return xx;}int main(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;


   









本文转自:

http://blog.csdn.net/tutuboke/article/details/51042629