【问题标题】:Best Practices? Converting from pointers to Unique_Ptrs最佳实践?从指针转换为 Unique_Ptrs
【发布时间】:2021-08-05 21:40:16
【问题描述】:

我正在尝试将裸指针转换为智能指针。 但我不太确定如何在使用唯一指针时保留 currentBar(也将位于 myBars 中)

Class Foo
{
  public:
     Bar* getCurrentBar();
     //!! other stuff not important
  private:
     Bar* currentBar;
     std::vector<Bar *> myBars;
  
};

我不认为我应该使用共享指针,因为唯一拥有对象所有权的是 Foo,

Class Foo
{
   public:
      std::unique_ptr<Bar> getCurrentBar(); //? returns currentBar, whatever currentBar is;
   private:
      std::unique_ptr<Bar> currentBar; //? What do I do here?
      std::vector<std::unique_ptr<Bar>> myBars;
 };

上述方法不起作用,但我想做与上述类似的事情。我该怎么做呢? (我宁愿不使用共享指针)。

【问题讨论】:

  • 如果 Foo 应该拥有指针,即使在有人调用 getCurrentBar() 之后,也不要返回 unique_ptr。实现它:Bar* getCurrentBar() { return currentBar.get(); }.- 此外,您不能在 unique_ptrcurrentBarmyBars 中包含相同的指针。顺便说一句,您是否必须使用指针?为什么不std::vector&lt;Bar&gt; myBars;
  • 不是问题的主题,但是一旦您从公共 getter 返回指向非常量或非常量引用的指针,您就不需要将成员设为私有。通过调用getCurrentBar,调用者可以直接访问该成员,绕过所有访问保护

标签: c++ smart-pointers unique-ptr


【解决方案1】:

非拥有原始指针没有错。使用向量中的unique_ptr 来管理生命周期,然后为您的接口使用常规指针或引用。看起来像

Class Foo
{
  public:
     Bar* getCurrentBar(); 
     // or Bar& getCurrentBar();
  private:
     Bar* currentBar;
     std::vector<std::unique_ptr<Bar>> myBars;
  
};

【讨论】:

  • 关于为什么std::unique_ptr&lt;Bar&gt; getCurrentBar(); 不好的说明:在制作返回的std::unique_ptr&lt;Bar&gt; 时,当前持有者将被剥夺所有权。请记住,唯一意味着只能有一个。如果您传递unique_ptr,则您正在转移所有权以保持唯一性。如果您不知何故有多个std::unique_ptrs 指向同一个对象,那么您已经违反了规则并且处于艰难时期。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2010-11-01
相关资源
最近更新 更多