我正在学习智能指针,以下是示例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
时,编译器只给出了警告。
shapes.emplace_back(std::make_unique<Square>())
,并使用了C++14。 - MemoriesabstractShape
中添加虚析构函数,即使它是默认的也要这样做。将virtual ~abstractShape() = default;
添加到该类中。这也应该能够让C++14的make_unique语义正确地连接起来。 点击查看实例。 - WhozCraig