c++ - 在顶层使用 shared_ptr 而不是 scoped_ptr 有什么优势吗?

标签 c++ shared-ptr scoped-ptr

我的团队对于指针容器在特定上下文中的使用存在一些分歧。请考虑:

int main() {
   // Top level. This is an important fact to the context
   // i.e. that the following instance is at this level
   // so that its members are essentially at program scope.
   MainClass mainClass;
   mainClass.run();
}

// A instance of a class derived from Buffer does something very complex
// (it has various handles to resources/allocated memory) so that you would
// never want to copy an instance.
class Buffer;

class MainClass {

   #make_decision_here_based_on_stack_overflow_responses
   shared_ptr<Buffer> buffer; // 1
   scoped_ptr<Buffer> buffer; // 2
   #end_decision

   MainClass() {
       // non-trivial initialisation of buffer with any of a number of derived classes:
       buffer.reset( ... )
   }    

   void run() {
       #make_decision_here_based_on_stack_overflow_responses
       SomeSubservientClass sub(*buffer);      // a
       SomeSubservientClass sub(buffer.get()); // b
       SomeSubservientClass sub(buffer);       // c
       #end_decision
       sub.do_stuff()
   }
};

(我希望你能理解这里的特殊预处理器代码,它实际上并不存在,但如果它存在就好了:)

我们目前拥有的代码处于状态“1b”(shared_ptr 成员,向下传递裸 ptr)但我们认为这不应该是这样。我很想知道任何人乍一看认为什么是最自然/合理和最安全的事情和理由。或者如果有人想建议“3”或“d”。我自己有意见,但还不想分享。

最佳答案

智能指针的选择就是所有权策略的选择。你必须问自己这个问题:

  • MainClassBuffer 实例的唯一所有者吗?还是存储在 MainClass 中的 Buffer 实例比 MainClass 对象存在时间更有意义? (或者如果 MainClass 成为更大系统的组件并失去其应用程序生命周期状态是否有意义?)

如果答案是有道理,使用共享指针。如果答案是sole owner/doesn't make sense,使用表达唯一所有权的东西 - scoped_ptr(或 std::unique_ptr,如果可用)。

如果您最终拥有唯一所有权,请使用选项“a”来传递对象。如果空指针是函数的有效输入,则函数只应采用指针参数。

如果您最终拥有共享所有权,则有两种可能的情况。要将缓冲区传递到共享所有权的地方,请传递 shared_ptr 本身。要将其传递到仅观察/修改的地方,请使用上面的 'a'。

关于c++ - 在顶层使用 shared_ptr 而不是 scoped_ptr 有什么优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17952182/

相关文章:

c++ - 对 scoped_ptr 的弱引用?

c++ - string::npos 如何知道我指的是哪个字符串?

c++ - unique_ptr 和 shared_ptr 的重载方法与多态性不明确

c++ - C++调用过程中对象被销毁怎么办

c++ - boost scoped_ptr/shared_ptr 持有大小与指向的对象大小不同的内存块

c++ - 在 scoped_ptr 出现异常时不调用析构函数

c++ - 使用 'free' 释放内存时出现分段冲突

c++ - AddFontResource + SetCurrentConsoleFontEx 不会更改控制台字体

c++ - 将一个十六进制拆分为 2 个十六进制值

c++ - 如果我删除类(class),shared_ptr 会被删除吗