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

J W*_*J W 2 c++ smart-pointers operator-overloading

我为自写类重载了operator +,并通过智能指针处理了这些类的实例。现在,我想知道是否没有更好的方法来利用运算符。此外,我不知道如何将它们重新打包到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()



Run Code Online (Sandbox Code Playgroud)

mol*_*ilo 5

对于“智能指针”,解除引用运算符已重载。
您应该像这样将它们加起来:

*a + *b
Run Code Online (Sandbox Code Playgroud)

如果要与结果共享对象,则可以从中创建共享对象:

auto c = std::make_shared<A>(*a + *b);
Run Code Online (Sandbox Code Playgroud)

如果您有原始指针,则可以执行以下操作:

auto c = new A(*a + *b);
Run Code Online (Sandbox Code Playgroud)

相似性不是巧合。

附带说明一下,除非您真的打算在多个所有者之间共享一个对象,否则您根本不应使用shared_ptr