何时使用shared_ptr和何时使用裸指针? [英] When to use shared_ptr and when to use raw pointers?
问题描述
class B;
class A
{
public:
A ()
: m_b(new B())
{
}
shared_ptr<B> GimmeB ()
{
return m_b;
}
private:
shared_ptr<B> m_b;
};
假设B是语义上不应该存在于A生命周期之外的类, B绝对没有意义B自己存在。 应< shared_ptr< B>
或 B *
?
Let's say B is a class that semantically should not exist outside of the lifetime of A, i.e., it makes absolutely no sense for B to exist by itself. Should GimmeB
return a shared_ptr<B>
or a B*
?
一般来说,完全避免使用C ++代码中的原始指针代替智能指针是一个好习惯吗?
我认为 shared_ptr
只应在有明确转让或分享时使用的所有权,我认为是非常罕见的情况下,一个函数分配一些内存,填充一些数据,并返回它,调用方和被调用者之间的理解,前者现在是负责的数据。
I am of the opinion that shared_ptr
should only be used when there is explicit transfer or sharing of ownership, which I think is quite rare outside of cases where a function allocates some memory, populates it with some data, and returns it, and there is understanding between the caller and the callee that the former is now "responsible" for that data.
推荐答案
我认为你的分析是正确的。在这种情况下,我也会返回一个裸的 B *
,甚至一个 [const] B&
保证不会为空。
Your analysis is quite correct, I think. In this situation, I also would return a bare B*
, or even a [const] B&
if the object is guaranteed to never be null.
我花了一些时间来精读智能指针,我得到了一些指导,告诉我在很多情况下该做什么:
Having had some time to peruse smart pointers, I arrived at some guidelines which tell me what to do in many cases:
- 如果返回一个对象的生命周期由调用者管理,则返回
std :: unique_ptr
。 - 返回
std :: shared_ptr
实际上是相当罕见的,并且当它有意义时,它通常是显而易见的:您向调用者指示它将延长指向对象的生命周期超过最初维护的对象的生命周期资源。从工厂返回共享指针也不例外:您必须这样做例如。当你使用std :: enable_shared_from_this
。 - 你很少需要
std :: weak_ptr
,除非你想了解lock
方法。这有一些用途,但他们是罕见的。在你的例子中,如果A
对象的生命周期从调用者的角度来看是不确定的,那么这将是需要考虑的事情。 - 如果您返回对调用程序无法控制的生命周期的现有对象的引用,则返回裸指针或引用。通过这样做,你告诉调用者一个对象存在,她不必照顾它的生命周期。如果不使用
nullptr
值,则应返回引用。
- If you return an object whose lifetime is to be managed by the caller, return
std::unique_ptr
. The caller can assign it to astd::shared_ptr
if it wants. - Returning
std::shared_ptr
is actually quite rare, and when it makes sense, it is generally obvious: you indicate to the caller that it will prolong the lifetime of the pointed-to object beyond the lifetime of the object which was originally maintaining the resource. Returning shared pointers from factories is no exception: you must do this eg. when you usestd::enable_shared_from_this
. - You very rarely need
std::weak_ptr
, except when you want to make sense of thelock
method. This has some uses, but they are rare. In your example, if the lifetime of theA
object was not deterministic from the caller's point of view, this would have been something to consider. - If you return a reference to an existing object whose lifetime the caller cannot control, then return a bare pointer or a reference. By doing so, you tell the caller that an object exists and that she doesn't have to take care of its lifetime. You should return a reference if you don't make use of the
nullptr
value.
这篇关于何时使用shared_ptr和何时使用裸指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!