矢量、unique_ptr 和 Push_back 错误

CH2*_*ain 5 c++ unique-ptr implicit-conversion

我正在学习智能指针,以下示例test.cpp

#include<iostream>
#include<vector>
#include<memory>

struct abstractShape
{
    virtual void Print() const=0;
};

struct Square: public abstractShape
{
    void Print() const override{
        std::cout<<"Square\n";
    }
};

int main(){
    std::vector<std::unique_ptr<abstractShape>> shapes;
    shapes.push_back(new Square);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码有编译错误“c++ -std=c++11 test.cpp”:

smart_pointers_2.cpp:19:12: error: no matching member function for call to 'push_back'
    shapes.push_back(new Square);
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解释一下这个错误吗?顺便说一句,当我更改push_back为时emplace_back,编译器仅给出警告。

son*_*yao 7

push_back需要一个std::unique_ptr,当传递像 一样的原始指针时new Square,这被认为是复制初始化,原始指针需要隐式转换为std::unique_ptr。隐式转换失败,因为std::unique_ptr来自原始指针的转换构造函数被标记为explicit

emplace_backstd::unique_ptr之所以有效,是因为它将参数转发到直接初始化形式的构造函数和构造元素,其中考虑了explicit转换构造函数。

参数 args... 作为 转发给构造函数std::forward<Args>(args)...