std :: shared_ptr的用法 [英] Usage of std::shared_ptr

查看:149
本文介绍了std :: shared_ptr的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用std :: shared_ptr作为double数组?另外,使用shared_ptr的优点/缺点。

解决方案

这取决于你以后。如果你只是想要一个可调整大小的双倍数组,请用

  std :: vector< double& 

示例:

 code> std :: vector< double> v; 
v.push_back(23.0);
std :: cout<< v [0];

如果共享所述数组的所有权对您很重要,请使用eg

  std :: shared_ptr< std :: vector< double>> 

示例:

 code> std :: shared_ptr< std :: vector< double>> v1(new std :: vector< double>); 
v1-> push_back(23.0);
std :: shared_ptr< std :: vector< double>> v2 = v1;
v2> push_back(9.0);
std :: cout<< (* v1)[1];

或者,Boost有

  boost :: shared_array 

请参阅:



http://www.boost。 org / libs / smart_ptr / shared_array.htm



至于shared_ptr的几个优点/缺点:



优点




  • 基于引用计数的自动共享资源释放有助于避免内存泄漏和其他与未获取释放相关的问题



缺点 / p>


  • 存储引用计数的内存开销对小对象可能很重要。

  • 性能可能比对于原始指针(但测量此)


How can I use std::shared_ptr for array of double? Additionally what are advantages/disadvantages of using shared_ptr.

解决方案

It depends on what you're after. If you just want a resizable array of doubles, go with

std::vector<double>

Example:

std::vector<double> v;
v.push_back(23.0);
std::cout << v[0];

If sharing the ownership of said array matters to you, use e.g.

std::shared_ptr<std::vector<double>>

Example:

std::shared_ptr<std::vector<double>> v1(new std::vector<double>);
v1->push_back(23.0);
std::shared_ptr<std::vector<double>> v2 = v1;
v2->push_back(9.0);
std::cout << (*v1)[1];

Alternatively, Boost has

boost::shared_array

which serves a similar purpose. See here:

http://www.boost.org/libs/smart_ptr/shared_array.htm

As far as a few advantages/disadvantages of shared_ptr go:

Pros

  • Automated shared resource deallocation based on reference counting - helps avoid memory leaks and other problems associated with things not getting deallocated when they should be
  • Can make it easier to write exception-safe code

Cons

  • Memory overhead to store the reference count can be significant for small objects
  • Performance can be worse than for raw pointers (but measure this)

这篇关于std :: shared_ptr的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆