Create a boost::shared_ptr to an existing variable

前端 未结 4 1180
星月不相逢
星月不相逢 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:59

    What you wrote won't work because the constructor of shared_ptr you're looking for is explicit, so you'd need to write it like so

    boost::shared_ptr a_ptr(&a); // Don't do that!
    

    The problem with that however, is that delete will be called on the stored value of a_ptr. Since in your example a has automatic storage duration, this is very bad. So we pass in a custom deleter too:

    boost::shared_ptr a_ptr(&a, noop_deleter);
    

    An implementation of noop_deleter for C++11:

    auto noop_deleter = [](int*) {};
    

    C++03 version:

    // Can't be put in local scope
    struct {
        void
        operator()(int*) const
        {}
    } noop_deleter;
    

提交回复
热议问题