1. 头文件:<memory>
  2. 通过shared_ptr的构造函数,可以让shared_ptr对象托管一个new运 算符返回的指针,写法如下:
    shared_ptr<T> ptr (new T);
    此后ptr就可以像 T 类型的指针一样来使用,即 ptr 就是用new动 态分配的那个对象,而且不必操心释放内存的事。
  3. 多个shared_ptr对象可以同时托管一个指针,系统会维护一个托管计数。当无shared_ptr托管该指针时,delete该指针。
  4. shared_ptr对象不能托管指向动态分配的数组的指针,否则程序运行会出错。
  5. 程序示例及结果如下。
struct A
{
    int n;
    A(int v = 0):n(v){}
    ~A(){cout << n << " destructor"<< endl;}
};
int main()
{
    shared_ptr<A> sp1(new A(2)); //sp1托管A(2)
    shared_ptr<A> sp2(sp1); //sp2也托管A(2)
    cout << "1)" << sp1->n << ","<<sp2->n<<endl;
    shared_ptr<A> sp3;
    A *p = sp1.get(); // p指向A(2)
    cout<< "2)" << p->n << endl;
    sp3 = sp1;  //sp3也托管A(2)  
    cout << "3)" << (*sp3).n << endl;
    sp1.reset();  //sp1放弃托管A(2)
    if (!sp1)
        cout << "4)sp1 is null"<<endl;
    A *q = new A(3);
    sp1.reset(q); // sp1托管q
    cout << "5)"<<sp1->n<<endl;
    shared_ptr<A> sp4(sp1); //sp4托管A(3)
    shared_ptr<A> sp5;
    //sp5.reset(q); 不妥,**该操作并不会增加对q的托管计数**会因q被delete两次而导致程序出错
    sp1.reset(); //sp1放弃托管A(3)
    cout<<"before end main" << endl;
    sp4.reset(); //sp4放弃托管A(3)
    cout<<"end main" << endl;
    return 0;  //程序结束,会delete掉A(2) 
}

IEWO5$2HW\)E$II3RIL47BC9.png


巴旦木
1 声望0 粉丝