简体   繁体   English

有没有更好的方法来添加两个智能指针?

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

I overloaded the operator+ for a self written class further I deal with instances of these class via smart pointers. 我重载了运算符+进一步自编写的类我通过智能指针处理这些类的实例。 Now I am wondering if there isn't a better way to make use of the operator. 现在我想知道是否有更好的方法来使用运算符。 Further I do not get how to pack them back into a shared_ptr. 此外,我不知道如何将它们打包回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()



The dereference operator is overloaded for the "smart pointers". 解除引用运算符因“智能指针”而过载。
You should add them up like this: 你应该像这样添加它们:

*a + *b

If you want a shared object with the result, you make a shared object from it: 如果您希望共享对象包含结果,则可以从中创建共享对象:

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

If you had raw pointers you would do this: 如果你有原始指针,你会这样做:

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

The similarity is not a coincidence. 相似性并非巧合。

On a side note, unless you really intend to share an object among multiple owners, you should not be using shared_ptr at all. 另外,除非您真的打算在多个所有者之间共享对象,否则您根本不应该使用shared_ptr

Is there a better way to add two smart pointers? 有没有更好的方法来添加两个智能指针?

You cannot add smart pointers. 您无法添加智能指针。 What you're doing here is indirecting through smart pointers and adding the pointed objects. 你在这里做的是通过智能指针和添加指向的对象来间接。

The call to get() is redundant. 对get()的调用是多余的。 You can indirect through the smart pointer directly: *a + *b . 您可以直接通过智能指针间接: *a + *b

Further I do not get how to pack them back into a shared_ptr 此外,我不知道如何将它们打包回shared_ptr

A simple way to create a shared pointer is std::make_shared . 创建共享指针的一种简单方法是std::make_shared

You can implement an operator for a shared_ptr specialization: 您可以为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);
}

and simple use 而且使用简单

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

A full example could be 一个完整的例子可能是

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);
}

So you could use 所以你可以使用

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

and also 并且

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