2

我在重构一个使用 unique_ptrs 的 std::vector 的类时遇到了一些麻烦。我目前有一堂类似于:

class DataItemA
{
  // various data members
};

class DataItemB
{
  // various data members
};

class PointerOwner
{
public:
  PointerOwner();
  ~PointerOwner();

  void ComplexCalculationOnItemA()
  {
    for (auto itr = aItemsIOwn.begin(); itr != aItemsIOwn.end(); ++itr)
    {
      DataItemA& itemA= (**itr);

      // complex calculations that also reference DataItemB items
    }
  } 

  // methods to add / remove items from the collections
private:
  // This class owns the DataItems and control their lifetime.
  // The objects cannot live outside of this instance.
  std::vector<std::unique_ptr<DataItemA>> aItemsIOwn;
  std::vector<std::unique_ptr<DataItemB>> bItemsIOwn;
};

我正在重构该类以将复杂的计算提取到另一个类,并且不确定如何将 unique_ptrs 的向量传递给另一个类并清楚地“声明”该计算不拥有指针。是否合理:

class ComplexItemAProcessor
{
  ComplexItemAProcessor(const std::vector<std::unique_ptr<DataItemA>>& itemsToProcess)
  {
    // can I store the itemsToProcess in a member variable
  }

  SomeReturnType runCalcuation() {}

private:

  // store the reference to calculation
}  

或者这样做更好:

class ComplexItemAProcessor
{
  ComplexItemAProcessor()
  {

  }

  SomeReturnType runCalcuation(const std::vector<std::unique_ptr<DataItemA>>& itemsToProcess)
  {
    // process the collection as per original class
  }
} 

ComplexItemAProcessor 的生命周期将被限制在原始方法的范围内。

class PointerOwner
{
public:
  PointerOwner();
  ~PointerOwner();

  ComplexCalculationOnItemA()
  {
    ComplexItemAProcessor processor; /** ? pass here **/

    SomeReturnType result = processor.runCalcuation(/* ? pass here */);
  } 
private:
  // This class owns the DataItems and control their lifetime.
  // The objects cannot live outside of this instance.
  std::vector<std::unique_ptr<DataItemA>> aItemsIOwn;
  std::vector<std::unique_ptr<DataItemB>> bItemsIOwn;
};

这些中的任何一个都比另一个更好吗?对我来说两者都不是正确的,但这可能是我对智能指针的有限经验。是否有另一种方法可以让另一个类在不转移所有权的情况下处理向量?

我认为我不需要 shared_ptrs 因为 PointerOwner 是唯一的所有者。

4

0 回答 0