向量错误,unique_ptr,和 push_back

error with vector, unique_ptr, and push_back

我正在学习智能指针,用下面的例子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;
}

以上代码出现编译错误 "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);

谁能帮我解释一下错误?顺便说一句,当我将push_back更改为emplace_back时,编译器只给出警告。

push_back需要一个std::unique_ptr,当传递像new Square这样的原始指针时,它被认为是copy-initialization,需要将原始指针转换为[=11] =] 含蓄地。隐式转换失败,因为 std::unique_ptr 来自原始指针的转换构造函数被标记为 explicit.

emplace_back 之所以有效,是因为它将参数转发给 std::unique_ptr 的构造函数并以 direct-initialization 形式构造元素,后者考虑了 explicit 转换构造函数。

The arguments args... are forwarded to the constructor as std::forward<Args>(args)....