【C++】boost::shared_ptr boost::make_shared

时间:2023-03-09 08:33:14
【C++】boost::shared_ptr boost::make_shared
一、shared_ptr
  1. shared_ptr作为一个动态分配的对象,当最后一个指向其内容的指针销毁(destroyed)或重置(reset),其指向的内容会被销毁(deleted)。不再需要显式调用delete释放指针指向的内存空间。
  2. shared_ptr的构造还需要new调用,这导致了代码中的某种不对称性。虽然shared_ptr很好地包装了new表达式,但过多的显式new操作符也是个问题。举例如下,
shared_ptr<double[]> p1( new double[] );
shared_ptr<double[]> p2( new double[n] );

3. shared_ptr是一个引用计数智能指针,用于共享对象的所有权,也就是说它允许多个指针指向同一个对象。

二、make_shared

构造shared_ptr时,比new更安全、更高效的方法是make_shared(使用系统默认new操作),allocate_shared(允许用户指定allocate函数)。

优势:new会有两次内存分配,一次是生成对象( new int() ),一次是引用计数

make_shared把两次合并成了一次,官方说法是:

它可以只用内存分配完成对象分配和相关控制块分配,消除相当一部分创建shared_ptr的开销(Besides convenience and style, such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr's construction overhead.)。

boost::shared_ptr<std::string> x = boost::make_shared<std::string>("hello, world!");
std::cout << *x;
// 构造一个string指针
boost::shared_ptr<vector<int> > spv = boost::make_shared<vector<int> >(, );
// 构造一个vector指针