NULL pointer with boost::shared_ptr?(带有 boost::shared_ptr 的 NULL 指针?)
问题描述
什么是等价于以下内容:
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_ptrvec.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.
这篇关于带有 boost::shared_ptr 的 NULL 指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有 boost::shared_ptr 的 NULL 指针?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
