shared_ptr的注意点

对于C++新手而言,面对复杂的项目中指针的四处传递,或者异常后的处理,很容易引起申请了内存没有释放的问题,c++11给出了智能指针来简化这一问题,常用的是shared_ptr。shared_ptr构造出的对象来管理一块内存,结构如下:

其中ptr指向了一块内存空间,ret_count存储了有多少shared_ptr对象引用了这块内存。当引用计数为0时,删除这块内存。但是使用它如果用的不恰当,也会引发一些问题,我个人觉得,如果要使用shared_ptr,那就全部用它,不要再用裸指针 。因为裸指针不是通过shared_ptr对象的传递那就不会改变它的引用计数。 比如下面的代码:

int *q;
{
	int *p = new int(10);
	q = p;
	shared_ptr<int> sp(p);
	cout << sp.use_count()<<endl;// use_count等于1
}
cout << *q;

在局部作用域结束后,sp释放了引用的那块内存,此时再访问q已经失效了。而如果改成下面的写法,就可以正确访问,并且正确释放内存。
 

shared_ptr<int> q;
{
	int *p = new int(10);
	shared_ptr<int> sp(p);
	q = sp;
	cout << sp.use_count()<<endl;
}
cout << *q;

同样的,像这种问题还有,比如用shared_ptr指向同一块裸指针分配的空间时也会出现问题,比如下面的代码
 

{ 
		char*p = new char[128];	
		shared_ptr<char> sp(p);
		shared_ptr<char> sp2 (p);
		cout << sp.use_count(); // 1
		cout << sp2.use_count(); // 1
		//此处会两次调用delete p;
}

在局部作用域结束后,其实两个shared_ptr的引用计数都为1,所以就会调用两次delete,就会引发异常。
shared_ptr中有一个get函数,可以获得其原始指针,但我觉得get后最好不要赋值给其他指针,否则可能会写出下面的代码:
 

shared_ptr<int> p = make_shared<int>(42);
cout << *p;
int *q = p.get();
{
	shared_ptr<int> sp(q);
} // 程序块结束,q被销毁,指向的内存被释放。
cout << *p;//此时p内存已被释放,此处引用一个野指针会异常

在局部作用域中sp引用计数为1,结束后销毁q指向的内存,q是p的get获得,所以就是释放的p的内存,此时再访问p就会出问题。
类似的,还有下面的情况,不要将get后的指针在reset中引用
 

{
	shared_ptr<int>sp(new int(10));
	shared_ptr<int>sp2(new int(20));
	sp.reset(sp2.get());//此处会释放sp的内存

	cout << *sp << sp.use_count() << endl;
	cout << *sp2 << sp2.use_count() << endl;
}

第三行代码处sp调用reset后会删除sp本身所在的内存,然后引用sp2的内存,输出时*sp与*sp2都为20,但是由于通过get方法构造的,他们的use_count都为1,所以在程序块结束时分别调用delete又会删除同一块内存两次。
另外就是循环引用问题
引用其他文章的一段代码
 

class parent;
class children;

typedef shared_ptr<parent> parent_ptr;
typedef shared_ptr<children> children_ptr;

class parent
{
public:
    ~parent() { std::cout << "destroying parent\n"; }

public:
    //weak_ptr<children>  children;
    children_ptr children;
};

class children
{
public:
    ~children() { std::cout << "destroying children\n"; }

public:
    parent_ptr parent;
    //weak_ptr<parent>  parent;
};

void test()
{
    A a;
    B b;
    parent_ptr father(new parent());
    children_ptr son(new children);

    father->children = son;
    cout << son.use_count() << endl;


    son->parent = father;
    cout << father.use_count() << endl;
}

void main()
{
    std::cout << "begin test...\n";
    test();
    std::cout << "end test.\n";
    cin.get();
}

原文:https://blog.csdn.net/leichaowen/article/details/53064294 

由于father类中持有son类的shared_ptr,son类中也持有father类的shared_ptr,导致在作用域结束时引用计数都为2,引起内存泄露,解决办法就是将成员变量改为weak_ptr,week_ptr专门为了配合shared_ptr而生,它不修改引用计数,可通过expired函数检查是否有效。

最后就是在多线程下的问题,shared_ptr的引用计数本身是安全且无锁的。但是对于读写则需要加锁,引用一段代码:
 

shared_ptr<long> global_instance = make_shared<long>(0);
std::mutex g_i_mutex;
 
void thread_fcn()
{
    //std::lock_guard<std::mutex> lock(g_i_mutex);
 
    //shared_ptr<long> local = global_instance;
 
    for(int i = 0; i < 100000000; i++)
    {
        *global_instance = *global_instance + 1;
        //*local = *local + 1;
    }
}
 
int main(int argc, char** argv)
{
    thread thread1(thread_fcn);
    thread thread2(thread_fcn);
 
    thread1.join();
    thread2.join();
 
    cout << "*global_instance is " << *global_instance << endl;
 
    return 0;
}

在线程函数thread_fcn的for循环中,2个线程同时对*global_instance进行加1的操作。这就是典型的非线程安全的场景,最后的结果是未定的,运行结果如下:
*global_instance is 197240539
如果使用的是每个线程的局部shared_ptr对象local,因为这些local指向相同的对象,因此结果也是未定的,运行结果如下:
*global_instance is 160285803
因此,这种情况下必须加锁,将thread_fcn中的第一行代码的注释去掉之后,不管是使用global_instance,还是使用local,得到的结果都是:
*global_instance is 200000000

https://stackoverflow.com/questions/14482830/stdshared-ptr-thread-safety

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值