英文:
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 <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); // ok
A a2 = data; // not ok
return 0;
}
答案1
得分: 3
A a2 = data; // 不可以
这不起作用是因为编译器需要执行两次转换(`shared_ptr<derived>` -> `shared_ptr<base>` -> `A`),但它只能隐式执行一次。
要修复它,你可以添加一个重载的构造函数,如果你知道`derived`:
A(std::shared_ptr<derived> x) : A(static_cast<std::shared_ptr<base>>(x)) {}
或者你可以一开始将指针存储为`shared_ptr<base>`:
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<derived>
-> shared_ptr<base>
-> 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<derived> x) : A(static_cast<std::shared_ptr<base>>(x)) {}
or you can store your pointer as shared_ptr<base>
to begin with:
std::shared_ptr<base> data = std::make_shared<derived>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论