std::shared_ptr

来源:互联网 发布:tv域名能备案吗 编辑:程序博客网 时间:2024/05/20 16:45

std::share_ptr 允许多个指针执行同一个对象

当指向对象的最后一个shared_ptr被销毁时,share_ptr类会自动销毁此对象。

class Simple {public:    Simple(int param = 0) {        number = param;        std::cout << "Simple: " << number << std::endl;     }    ~Simple() {        std::cout << "~Simple: " << number << std::endl;    }    void PrintSomething() {        std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;    }public:    std::string info_extend;    int number;};void Test(){    std::shared_ptr<Simple> p1 = make_shared<Simple>(123);    p1->info_extend  = "abc";    printf("shardcount = %d\n",p1.use_count());    std::shared_ptr<Simple> p2 = p1;    printf("shardcount = %d\n",p1.use_count());    printf("shardcount = %d\n",p2.use_count());    p1->PrintSomething();    p2->PrintSomething();    // 删除p1的引用    p1.reset();    printf("shardcount = %d\n",p1.use_count());    printf("shardcount = %d\n",p2.use_count());    p2->PrintSomething();}

std::shared_ptr自身拷贝

void process(std::shared_ptr<Simple> ptr){    // 形参传递,拷贝一个std::shared_ptr user_count()会变成2    // 当函数退出后, 局部std::shared_ptr变量会销毁掉    printf("shardcount = %d\n",ptr.use_count()); //  2}void Test(){    std::shared_ptr<Simple> p1 = make_shared<Simple>(123);    p1->info_extend  = "abc";    printf("shardcount = %d\n",p1.use_count()); // 1    process(p1);    printf("shardcount = %d\n",p1.use_count()); // 1}

普通指针和智能指针

void process(std::shared_ptr<int> ptr){}int main(){    int *x = new int(2);    //process(x); // 错误,int* 不能装换为std::shared_ptr<int>    process(std::shared_ptr<int>(x)); // 合法, 但是内存会被释放,表达式临时对象    int j = *x; // x是一个悬空指针    cout << j << endl; // 不能打印出 2    return 0;}

不要用.get()初始化另一个智能指针或为智能指针赋值

get用来将指针的访问权限传递给代码,你只有在确定代码不会调用delete指针的情况下,才能使用get。特别是,永远不要用get初始化另一个智能指针或者为另一个智能指针赋值。
void process(std::shared_ptr<int> ptr){}int main(){    std::shared_ptr<int> p1(new int(2));    process(std::shared_ptr<int>(p1.get())); // 错误    return 0;}

注意使用get()返回的内置智能后,需要判断是否还有效

std::shared_ptr<int> p1(new int(100));auto p = p1.get();cout << *p << endl; // 100cout << p1.use_count() << endl; // 1p1.reset();cout << p1.use_count() << endl; //0 cout << *p << endl; // p 指向 无效的地址, 打印无效的值

不要delete 内置指针

void func(){    std::shared_ptr<int> p1(new int(100));    auto p = p1.get();    cout << *p << endl; // 100    cout << p1.use_count() << endl; // 1    delete p;    cout << "func endl" << endl;}


std::shared_ptr 环问题的内存泄漏,参考如下
http://blog.csdn.net/shanno/article/details/7363480

0 0
原创粉丝点击