Create a boost::shared_ptr to an existing variable

前端 未结 4 1181
星月不相逢
星月不相逢 2020-12-08 07:32

I have an existing variable, e.g.

int a = 3;

How can I now create a boost::shared_ptr to a? For example:

4条回答
  •  孤城傲影
    2020-12-08 07:45

    although you should put the variable into a managed pointer on it's creation to do it from an existing pointer.

    int *a=new int;
    boost::shared_ptr a_ptr(a);
    

    That said you most definitely do not want to be putting stack variables into shared_ptr BAD THINGS WILL HAPPEN

    If for some reason a function takes shared_ptr and you only have a stack varaible you are better off doing this:

    int a=9;
    boost::shared_ptr a_ptr=boost::make_shared(a);
    

    See here:

    http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/make_shared.html

    also it is worth noting that shared_ptr is in the c++11 standard if you are able using that. You can use auto in combination with make_shared like Herb Sutter notes in the build talk.

    #include 
    
    int a=9;
    auto a_ptr=std::make_shared(9);
    

提交回复
热议问题