[英]weak_ptr vs unique_ptr reference - passing interface impl to other object
Here is an example code: 这是一个示例代码:
class Interface
{
public:
virtual ~Interface(){}
virtual void fun() = 0;
};
class InterfaceImpl: public Interface
{
public:
void fun() override
{}
};
class B
{
public:
B(const std::shared_ptr<Interface>& impl /*std::unique_ptr<Interface>& impl* ?*/): impl_(impl){}
private:
std::weak_ptr<Interface> impl_;
//std::unique_ptr<Interface>& impl_; ?
};
class A
{
public:
A(): impl_(std::make_shared<InterfaceImpl>()), b(impl_){}
private:
std::shared_ptr<Interface> impl_;
//std::unique_ptr<Interface> impl_ ?
B b;
};
Class A contains an interface implementation and other object of type B. That object also need to use an interface implementation. A类包含接口实现和B类型的其他对象。该对象还需要使用接口实现。 I wonder which types of smart pointers should be used to create interface impl in class A and pass that impl to class B. Should I use shared_ptr in class A and weak_ptr in class B or unique_ptr in class A and a reference to unique ptr in class B ?
我想知道应该使用哪种类型的智能指针在类A中创建接口impl并将该impl传递给类B.我应该在类A中使用shared_ptr,在类A中使用weak_ptr还是在类A中使用unique_ptr,并在类中使用对唯一ptr的引用B?
I believe the default choice should be that A
, that owns the Interface
, should hold it by unique_ptr
. 我认为默认选择应该是拥有
Interface
A
应该由unique_ptr
。 Then B
, which does not own the Interface
, should hold it by normal reference or raw pointer. 那么,不拥有
Interface
B
应该通过普通引用或原始指针来保存它。
A reference to a unique_ptr
rarely makes sense. 对
unique_ptr
的引用很少有意义。 It offers no additional safety guarantees over a raw pointer or a normal reference but adds confusion over ownership. 它不会对原始指针或普通参考提供额外的安全保证,但会增加对所有权的混淆。
class Interface
{
public:
virtual ~Interface(){}
virtual void fun() = 0;
};
class InterfaceImpl: public Interface
{
public:
void fun() override
{}
};
class B
{
public:
B(const Interface& impl): impl_(impl){}
private:
const Interface& impl_;
};
class A
{
public:
A(): impl_(std::make_unique<InterfaceImpl>()), b(*impl_){}
private:
std::unique_ptr<Interface> impl_;
B b;
};
This is assuming the lifetime of B
is shorter than the lifetime of A
so that B
can guarantee that the Interface
is alive. 这假设
B
的寿命短于A
的寿命,因此B
可以保证Interface
处于活动状态。 If you can't make that guarantee then you can start thinking about shared_ptr
and weak_ptr
pair but I don't think that should be your first choice. 如果你不能保证那么你可以开始考虑
shared_ptr
和weak_ptr
对,但我认为这不应该是你的首选。 It looks like in your case you can make that guarantee. 在您的情况下,您可以做出保证。
As for whether B
should hold a normal reference or a raw pointer that comes down to whether impl_
can be null (which doesn't seem to be the case here). 至于
B
是否应该持有一个普通引用或一个原始指针,该指针归结为impl_
是否为null(这里似乎不是这种情况)。 Also, holding a reference restricts what you can do with B
. 此外,持有参考限制了您可以用
B
做什么。 It makes it unassignable and you can't reseat the reference to point to a different impl. 它使它无法分配,你不能重新引用指向不同的impl。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.