将对象移动到std::shared_ptr

std::move of an object to a std::shared_ptr

本文关键字:shared ptr std 对象 移动      更新时间:2023-10-16

给定以下模板化类:

template<typename Container>
Class A
{
public:
A() : {}
bool push(std::shared_ptr<Container> container) 
{
ptr_vec.emplace_back(container)
}
void load(Container c) 
{
push(std::make_shared((Container)std::move(c));
}
private:
std::vector<std::shared_ptr<Container>> ptr_vec;
};

以及main.cpp中的以下代码:

A<std::string> my_A {};
my_A.load("Hello");

我得到以下错误:

错误:对"make_shared(std::__cxx11::basic_string<char>("的调用没有匹配的函数

有人能解释一下这个错误以及如何修复它吗?

给定的代码有很多拼写错误。

但是,如果您修复了这些(此处:https://godbolt.org/z/M81qnh),错误来自std::make_shared函数,它是一个模板化函数。它需要明确指定的第一个参数

push(std::make_shared<Container>(std::move(c)));
//                   ^^^^^^^^^^