将派生类的unique_ptr添加到基类unique_ptr的向量中

5 c++ inheritance vector unique-ptr move-semantics

我有一个unique_ptr,我想添加到vector>.

unique_ptr<Derived> derivedObject;
vector<unique_ptr<Base>> vec;

vec.push_back(derivedObject) // Invalid arguments
Run Code Online (Sandbox Code Playgroud)

Mar*_*lny 8

unique_ptr保证它只有一个指向内存的指针,所以你不能只将它复制到向量中,你需要移动它:

vec.push_back(std::move(derivedObject));
Run Code Online (Sandbox Code Playgroud)

如果你看一下unique_ptr构造函数(http://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr),你看,这个类没有实现复制构造函数,而是实现了移动构造函数(http:/ /en.cppreference.com/w/cpp/language/move_constructor).


πάν*_*ῥεῖ 5

这是因为您无法复制std::unique_ptr. 该问题可以使用以下方法解决std::move()

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

struct Base {
};

struct Derived : public Base {
};

int main()
{
    std::unique_ptr<Derived> derivedObject;
    std::vector<std::unique_ptr<Base>> vec;

    vec.push_back(std::move(derivedObject));    
               // ^^^^^^^^^^             ^
}
Run Code Online (Sandbox Code Playgroud)

这是一个现场演示