c ++:can vector <Base>包含Derived类型的对象吗?

Bee*_*zum 7 c++ polymorphism vector object-slicing

标题基本概括了所有内容.基本上,这样做是合法的:

class Base {
    //stuff
}

class Derived: public Base {
    //more stuff
}

vector<Base> foo;
Derived bar;
foo.push_back(bar);
Run Code Online (Sandbox Code Playgroud)

基于我见过的其他帖子,以下是可以的,但我不想在这种情况下使用指针,因为它更难以使其线程安全.

vector<Base*> foo;
Derived* bar = new Derived;
foo.push_back(bar);
Run Code Online (Sandbox Code Playgroud)

eca*_*mur 14

不,Derived对象将被切片:所有其他成员将被丢弃.

而不是原始指针,使用std::vector<std::unique_ptr<Base> >.