boost::shared_ptr boost::make_shared

来源:互联网 发布:美工招聘信息 编辑:程序博客网 时间:2024/06/07 06:39

1. boost::shared_ptr

    1.1 shared_ptr作为一个动态分配的对象,当最后一个指向其内容的指针销毁(destroyed)或重置(reset),其指向的内容会被销毁(deleted)。

example:

shared_ptr<double[1024]> p1( new double[1024] );shared_ptr<double[]> p2( new double[n] );

    1.2 避免使用未命名的shared_ptr临时保存类型,例如:

void f(shared_ptr<int>, int);int g();void ok(){    shared_ptr<int> p( new int(2) );    f( p, g() );}void bad(){    f( shared_ptr<int>( new int(2) ), g() );}

     由于函数调用参数是无需的,有可能先执行new int(2) , 再执行 g(), 如果这是g()抛出异常,可能永远不能执行shared_ptr的构造函数。推荐使用安全,快速的的make_shared和allocate_shared函数。(boost/make_shared.hpp

    1.3 常用函数

    reset()

    get()

    unique()

    swap()

    等。


2. make_shared

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

    2.2 跟new比较

    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.)。

example:

boost::shared_ptr<std::string> x = boost::make_shared<std::string>("hello, world!");std::cout << *x;

3. 综合分析

#include <iostream>#include <boost/make_shared.hpp>#include <thread> typedef std::function<void ()> fp;using namespace std;class Bar{public:    Bar()    {        printf ("Bar init\n");    }    void print ()    {            printf ("in the bar \n");            sleep(3);    }};int main(){    std::vector<boost::shared_ptr<thread> > kafka_threads;    for (int i = 0; i < 2; ++i) {      //生成Bar类型shared_ptr,这个时候会创建了Bar对象,调用构造函数;      auto kafka_service = boost::make_shared<Bar>();                 cout << "push_back thread: " << i << endl;      kafka_threads.push_back(                  //生成新thread,用bind函数绑定Bar成员函数,并作为thread的执行函数,这个时候thread已经开始运行了;          boost::make_shared<thread>(std::bind(&Bar::print, kafka_service)));    }    for (int i = 0; i < 2; ++i) {      kafka_threads[i]->join();    }}





0 0
原创粉丝点击