【问题标题】:std::move of an object to a std::shared_ptrstd::move 对象到 std::shared_ptr
【发布时间】:2020-11-04 03:59:54
【问题描述】:

给定以下模板类:

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)'

谁能解释一下这个错误,以及如何解决它?

【问题讨论】:

    标签: c++ class c++11 templates smart-pointers


    【解决方案1】:

    你给的代码有很多错别字。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-21
      • 2021-08-28
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 2016-07-15
      • 1970-01-01
      相关资源
      最近更新 更多