带有 boost::shared_ptr 的 NULL 指针?

2021-12-24 00:00:00 pointers null c++ boost shared-ptr

什么是等价于以下内容:

What's the equivalent to the following:

std::vector<Foo*> vec;
vec.push_back(NULL);

什么时候处理boost::shared_ptr?是下面的代码吗?

when dealing with boost::shared_ptr? Is it the following code?

std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());

注意:我可能会推回很多这样的对象.我应该在某处声明一个全局静态 nullPtr 对象吗?这样就只需要构建其中一个:

Note: I may push back a lot of such objects. Should I declare a global static nullPtr object somewhere? That way only one of them would have to be constructed:

boost::shared_ptr<Foo> nullPtr;

推荐答案

您的建议(不带参数调用 shared_ptr 构造函数)是正确的.(使用值 0 调用构造函数是等效的.)我认为这不会比使用预先存在的 shared_ptr<调用 vec.push_back() 慢/code>,因为在这两种情况下都需要构造(直接构造或复制构造).

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;

这声明了一个全局对象 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;

请注意,如果您在多个翻译单元(源文件)中使用它,则需要为类命名(例如 _shared_null_ptr_type),移动 nullPtr<的定义/code> 对象到单独的 .cpp 文件,并在定义类的头文件中添加 extern 声明.

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.

相关文章