NULL指针与升压:: shared_ptr的? [英] NULL pointer with boost::shared_ptr?
问题描述
什么是等同于以下内容:
的std ::矢量<符* GT; VEC;
vec.push_back(NULL);
与的boost :: shared_ptr的
打交道时
?它是下列code?
的std ::矢量<提高:: shared_ptr的<富> > VEC;
vec.push_back(提高:: shared_ptr的<富>());
请注意:我可能推回很多此类对象。我要声明一个全局静态 nullPtr
对象的地方?要构成,即仅他们中的一个将具有
的boost :: shared_ptr的<富> nullPtr;
您的建议(调用的shared_ptr< T>
不带参数的构造函数)是正确的。 (呼叫值为0相当于构造函数)。我不认为这将是比任何调用速度较慢 vec.push_back()
以pre-现有的的shared_ptr< T>
,因为结构在两种情况下都需要(无论是直接施工或副本施工)
但如果你想更好的语法,你可以尝试以下code:
类{
上市:
模板< typename的T>
运营商的shared_ptr< T>(){返回的shared_ptr< T>(); }
} nullPtr;
这声明了一个全局对象 nullPtr
,使下面自然的语法:
的shared_ptr< INT>圆周率(新INT(42));
shared_ptr的< SomeArbitraryType> PSAT(新SomeArbitraryType(foonly));...PI = nullPtr;
PSAT = nullPtr;
请注意,如果你使用这个在多个翻译单元(源文件),你需要给一个类名(例如 _shared_null_ptr_type
),移动的定义在 nullPtr
对象到一个单独的.cpp文件,并添加的extern
的声明在头文件所在的类定义。
What's the equivalent to the following:
std::vector<Foo*> vec;
vec.push_back(NULL);
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>());
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;
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.
这篇关于NULL指针与升压:: shared_ptr的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!