无法使用赋值来构造一个对象,使用派生的 shared_ptr。

huangapple go评论66阅读模式
英文:

can't use assignment to construct an object using derived shared_ptr

问题

这是代码。我认为它显示了我的问题。那么,我该如何使它工作?

#include <memory>

struct base {
  virtual ~base();
};

struct derived : public base {};

struct A {
  A(std::shared_ptr<base> x) {}
};

int main() {
  std::shared_ptr<derived> data = std::make_shared<derived>();
  A a1(data);  // 可行
  A a2 = data; // 不可行
  return 0;
}

希望这个翻译有帮助。

英文:

This is the code. I think it shows my question. So how can I make it work?

#include &lt;memory&gt;

struct base {
  virtual ~base();
};

struct derived : public base {};

struct A {
  A(std::shared_ptr&lt;base&gt; x) {}
};

int main() {
  std::shared_ptr&lt;derived&gt; data = std::make_shared&lt;derived&gt;();
  A a1(data);  // ok
  A a2 = data; // not ok
  return 0;
}

答案1

得分: 3

A a2 = data; // 不可以

这不起作用是因为编译器需要执行两次转换(`shared_ptr&lt;derived&gt;` -&gt; `shared_ptr&lt;base&gt;` -&gt; `A`),但它只能隐式执行一次。

要修复它,你可以添加一个重载的构造函数,如果你知道`derived`:

A(std::shared_ptr<derived> x) : A(static_cast<std::shared_ptr<base>>(x)) {}

或者你可以一开始将指针存储为`shared_ptr&lt;base&gt;`:

std::shared_ptr<base> data = std::make_shared<derived>();

英文:
A a2 = data; // not ok

This doesn't work because the compiler would need to perform two conversions (shared_ptr&lt;derived&gt; -> shared_ptr&lt;base&gt; -> A), but it may only do one implicitly.

To fix it, you can either add an overloaded constructor, if you know derived:

A(std::shared_ptr&lt;derived&gt; x) : A(static_cast&lt;std::shared_ptr&lt;base&gt;&gt;(x)) {}

or you can store your pointer as shared_ptr&lt;base&gt; to begin with:

std::shared_ptr&lt;base&gt; data = std::make_shared&lt;derived&gt;();

huangapple
  • 本文由 发表于 2023年5月25日 16:44:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定