NULL pointer with boost::shared_ptr?

后端 未结 6 1005
悲哀的现实
悲哀的现实 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 21:15

    Your suggestion (calling the shared_ptr constructor with no argument) is correct. (Calling the constructor with the value 0 is equivalent.) I don't think that this would be any slower than calling vec.push_back() with a pre-existing shared_ptr, since construction is required in both cases (either direct construction or copy-construction).

    But if you want "nicer" syntax, you could try the following code:

    class {
    public:
        template
        operator shared_ptr() { return shared_ptr(); }
    } nullPtr;
    

    This declares a single global object nullPtr, which enables the following natural syntax:

    shared_ptr pi(new int(42));
    shared_ptr psat(new SomeArbitraryType("foonly"));
    
    ...
    
    pi = nullPtr;
    psat = nullPtr;
    

    Note that if you use this in multiple translation units (source files), you'll need to give the class a name (e.g. _shared_null_ptr_type), move the definition of the nullPtr object to a separate .cpp file, and add extern declarations in the header file where the class is defined.

提交回复
热议问题