NULL pointer with boost::shared_ptr?

后端 未结 6 1026
悲哀的现实
悲哀的现实 2020-12-12 20:35

What\'s the equivalent to the following:

std::vector vec;
vec.push_back(NULL);

when dealing with boost::shared_ptr

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 20:55

    You could declare a global nullPtr for shared_ptr. But if you pollute the global namespace, what would you call the global nullPtr for shared_ptr?

    Typically I declare the null ptr as a static in the class of the pointer.

    #include 
    
    class Foo; // forward decl
    typedef boost::shared_ptr FooPtr;
    class Foo
    {
    public:
        static FooPtr Null;
    }
    ...
    // define static in cpp file
    FooPtr Foo::Null;
    ...
    // use Foo Null
    vec.push_back(Foo::Null);
    

    That way each class has a static Null.

提交回复
热议问题