我对 C++ 比较陌生,这看起来像是一个菜鸟问题,但我无法用互联网上的其他资源解决它。
我正在尝试从参考中创建一个 shared_ptr 。我有以下 Book
类:
#include <memory>
#include "Author.hpp"
class Book
{
public:
void setAuthor(const Author& t_author);
private:
std::shared_ptr<Author> m_author;
}
这是我的 Author
课程:
#include <memory>
class Book;
class Author
{
public:
void addBook(const Book& t_book);
private:
std::vector<std::weak_ptr<Book>> m_books;
}
我厌倦了像这样实现 Book::setAuthor
方法:
void Book::setAuthor(const Author& t_author)
{
m_author = std::shared_ptr<Author>(&t_author);
}
但是,如果我尝试编译它,我会得到:
从 const Author* 到 Author* 的无效转换
从 sizeof 到 const 作者的无效转换
你能告诉我我的代码有什么问题吗?我也对weak_ptr进行了同样的尝试,但这也不起作用。
原文由 Cilenco 发布,翻译遵循 CC BY-SA 4.0 许可协议
Though, your error stems from the fact that the
std::shared_ptr<Author>
constructor in use expectsAuthor*
, but the expression&t_author
results to an object of typeconst Author*
另一个错误的事情:
想象一下调用
book.setAuthor(Author("Herb Sutter"));
,您将有一个 悬空指针,因为t_author
在该函数完成后将不复存在。您需要将对象复制或移动到您的
std::shared_ptr
实例中。尽可能使用std::make_shared<T>
创建您的std::shared_ptr<T>
对象。更好的是: