neak_ptr vs unique_ptr参考 - 传递接口inmand tos to其他对象
weak_ptr vs unique_ptr reference - passing interface impl to other object
这是一个示例代码:
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;
};
A类包含接口实现和类型B的其他对象。该对象还需要使用接口实现。我想知道应使用哪种类型的智能指针在A类中创建界面Inment ins Inmand Inment in Impt to类别。B?
我相信默认选择应该是拥有 Interface
的 A
应该由 unique_ptr
持有。然后,不拥有Interface
的B
应通过正常参考或原始指针保持。
对unique_ptr
的引用很少有意义。它没有提供原始指针或正常参考的其他安全保证,但会增加所有权的困惑。
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;
};
这是假设B
的寿命比A
的寿命短,因此B
可以保证Interface
还活着。如果您不能保证该保证,那么您可以开始考虑shared_ptr
和weak_ptr
对,但我认为这应该是您的首选。在您的情况下,您可以保证。
至于B
是否应保存正常参考或原始指针,该指针归结为impl_
是否可以为null(在这里似乎并非如此(。另外,持有参考可以限制您对B
的操作。它使其不可分配,您无法重设引用指向不同的inmand。
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- 对唯一 ptr 无效读取的引用向量
- C++ 类型转换基础 PTR 到派生 PTR 保存在引用类中
- 如何使用非类型参数传递模板化类的 Ref 或 Ptr
- 唯一 ptr 将所有权移动到包含对象的方法