简体   繁体   中英

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.

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.

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. You can indirect through the smart pointer directly: *a + *b .

Further I do not get how to pack them back into a shared_ptr

A simple way to create a shared pointer is std::make_shared .

You can implement an operator for a shared_ptr specialization:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM