std::shared_ptr

本文详细介绍了C++中智能指针std::shared_ptr的使用方法,包括其基本功能如引用计数、对象生命周期管理等,并通过具体示例说明了如何避免常见错误,例如不当使用get()方法及内存泄漏等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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; // 100

cout << p1.use_count() << endl; // 1

p1.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.youkuaiyun.com/shanno/article/details/7363480

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值