簡體   English   中英

有沒有更好的方法來添加兩個智能指針?

[英]Is there a better way to add two smart pointers?

我重載了運算符+進一步自編寫的類我通過智能指針處理這些類的實例。 現在我想知道是否有更好的方法來使用運算符。 此外,我不知道如何將它們打包回shared_ptr。

class A
{
  A operator + (A const & other)
  { //do some addition stuff and return new A}
};

std::shared_ptr<A> a, b;

//Currently I add them up like this
auto c = *a.get() + *b.get()



解除引用運算符因“智能指針”而過載。
你應該像這樣添加它們:

*a + *b

如果您希望共享對象包含結果,則可以從中創建共享對象:

auto c = std::make_shared<A>(*a + *b);

如果你有原始指針,你會這樣做:

auto c = new A(*a + *b);

相似性並非巧合。

另外,除非您真的打算在多個所有者之間共享對象,否則您根本不應該使用shared_ptr

有沒有更好的方法來添加兩個智能指針?

您無法添加智能指針。 你在這里做的是通過智能指針和添加指向的對象來間接。

對get()的調用是多余的。 您可以直接通過智能指針間接: *a + *b

此外,我不知道如何將它們打包回shared_ptr

創建共享指針的一種簡單方法是std::make_shared

您可以為shared_ptr特化實現運算符:

class A
{
...
};

std::shared_ptr<A> operator+(const std::shared_ptr<A>& a1, const std::shared_ptr<A>& a2)
{
  return std::make_shared<A>(*a1 + *a2);
}

而且使用簡單

std::shared_ptr<A> a1, a2;
std::shared_ptr<A> a3 = a1 + a2;

一個完整的例子可能是

class Value
{
private:
   int value;

public:
   Value(int value_): value(value_)
   {}

   Value operator+(Value other) const
   {
      return Value(value + other.value);
   }
};

std::shared_ptr<Value> operator+(const std::shared_ptr<Value>& a, const std::shared_ptr<Value>& b)
{
  return std::make_shared<Value>(*a + *b);
}

所以你可以使用

Value a, b;
Value c = a + b;

並且

std::shared_ptr<Value> pa, pb;
std::shared_ptr<Value> pc = pa + pb;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM