C ++中的空和std :: shared_ptr之间的区别是什么? [英] What is the difference between an empty and a null std::shared_ptr in C++?
问题描述
cplusplus.com shared_ptr
页面通话区分空 std :: shared_ptr
和 null shared_ptr
。 cppreference.com页面未显式调用区分,但使用空和比较 std :: shared_ptr
行为
中
nullptr
空和 shared_ptr
之间是否有区别?这样的混合行为指针有什么用例吗?是否非空的null shared_ptr
甚至有意义?在正常使用中是否会出现一个情况(即如果你没有明确构造一个),你可以结束一个空但是非空 shared_ptr
?
如果您使用的是Boost版本而不是C ++ 11版本,那么这些答案是否会改变?
这是 shared_ptr
行为的一个奇怪的角落。它有一个构造函数,允许你使拥有某事的 shared_ptr
和指向 >
模板<类Y>
shared_ptr(const shared_ptr< Y& r,T * ptr);
使用此构造函数构建的 shared_ptr
>分享所有权与 r
,但指向, ptr
(即调用 get()
或 operator->()
将返回 ptr
)。这对于 ptr
指向 r
拥有的对象的子对象(例如,数据成员)
您链接的页面调用了不含任何内容的 shared_ptr
shared_ptr
指向无( get()== nullptr
) null 。 ( ) shared_ptr
,但它不会很有用。一个空的但不是null null shared_ptr
本质上是一个非拥有的指针,可以用来做一些奇怪的事情,如传递一个指向堆栈上分配的某个指针的函数,期望一个 shared_ptr
(但是我建议你先在API里面加入 shared_ptr
)。
boost :: shared_ptr
也有这个构造函数,它们称为别名构造函数
The cplusplus.com shared_ptr
page calls out a distinction between an empty std::shared_ptr
and a null shared_ptr
. The cppreference.com page doesn't explicitly call out the distinction, but uses both "empty" and comparison to nullptr
in its description of std::shared_ptr
behavior.
Is there a difference between an empty and a null shared_ptr
? Is there any use case for such mixed-behavior pointers? Does a non-empty null shared_ptr
even make sense? Would there ever be a case in normal usage (i.e. if you didn't explicitly construct one) where you could end up with an empty-but-non-null shared_ptr
?
And do any of these answers change if you're using the Boost version instead of the C++11 version?
It's a weird corner of shared_ptr
behavior. It has a constructor that allows you to make a shared_ptr
that owns something and points to something else:
template< class Y >
shared_ptr( const shared_ptr<Y>& r, T *ptr );
The shared_ptr
constructed using this constructor shares ownership with r
, but points to whatever ptr
points to (i.e., calling get()
or operator->()
will return ptr
). This is handy for cases where ptr
points to a subobject (e.g., a data member) of the object owned by r
.
The page you linked calls a shared_ptr
that owns nothing empty, and a shared_ptr
that points to nothing (i.e., whose get() == nullptr
) null. (Empty is used in this sense by the standard; null isn't.) You can construct a null-but-not-empty shared_ptr
, but it won't be very useful. An empty-but-not-null shared_ptr
is essentially a non-owning pointer, which can be used to do some weird things like passing a pointer to something allocated on the stack to a function expecting a shared_ptr
(but I'd suggest punching whoever put shared_ptr
inside the API first).
boost::shared_ptr
also has this constructor, which they call the aliasing constructor.
这篇关于C ++中的空和std :: shared_ptr之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!