Your suggestion (calling the shared_ptr<T>
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<T>
, 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<typename T>
operator shared_ptr<T>() { return shared_ptr<T>(); }
} nullPtr;
This declares a single global object nullPtr
, which enables the following natural syntax:
shared_ptr<int> pi(new int(42));
shared_ptr<SomeArbitraryType> 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…