c++ - 如何/可能有一个 vector<unique_ptr<ABC>>?

标签 c++ vector unique-ptr abc

修改一些旧代码,在这些代码中,我手动处理指向抽象基类 (ABC) 的具体实例的原始指针 vector 的生命周期。

因此 vector 的所有者有一个虚拟的 dtor,它手动遍历并删除了 vector 的内容,等等。

由于 vector 的所有者拥有其中的元素,因此将其更改为 unique_ptr 的 vector 很有意义。

可悲的是,这似乎是不可能的?因为 vector<unique_ptr<type>>必须能够为 type 提供静态 dtor但是因为在这种情况下类型是 ABC,所以不可用,因此 vector不会编译...

还是我遗漏了什么?

例如:

struct ABC
{
    ABC() = default;
    virtual ~ABC() { } // need a vtable entry so that concrete subclasses will be deleted through the base dtor

    virtual std::unique_ptr<ABC> Clone() = 0;
    virtual void Foo() = 0;

    std::vector<std::unique_ptr<ABC>>   elements;
};

EDIT2:这是一个失败的完整示例:

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

struct ABC
{
    virtual ~ABC() { } // need a vtable entry so that concrete subclasses will be deleted through the base dtor

    virtual std::unique_ptr<ABC> Clone() = 0;
    virtual void Foo() = 0;

    std::vector<std::unique_ptr<ABC>>   elements;
};

struct Child : ABC
{
    std::unique_ptr<ABC> Clone() override { return std::make_unique<Child>(*this); }
    void Foo() override { };
};

struct Derived : Child
{
    std::unique_ptr<ABC> Clone() override { return std::make_unique<Derived>(*this); }
};

int main()
{
    std::unique_ptr<ABC> x;
    std::unique_ptr<ABC> c = std::make_unique<Child>();

    std::vector<std::unique_ptr<ABC>>   elements;
    elements.emplace_back(std::make_unique<Derived>());
    return 0;
}

最佳答案

当您尝试复制 Base 的实例时发生错误或派生自 Base 的类型的实例.默认复制构造函数将尝试复制 Base::elements , 它试图将它的每个元素复制到新的 vector 中.由于这些元素是 unique_ptr<Base>不允许复制。

这个例子重现了这个问题:

#include <memory>
#include <vector>

struct Base
{
    using PBase = std::unique_ptr<Base>;
    using VBase = std::vector<PBase>;

    VBase   elements;
};

int main()
{
    Base x;
    auto y = x; // This line causes the error

    return 0;
}

您可能需要实现自己的复制构造函数和复制赋值运算符,或者通过删除这些函数来禁止复制。使用 shared_ptr相反,如果浅拷贝适用于您的应用程序,则可能会起作用。

关于c++ - 如何/可能有一个 vector<unique_ptr<ABC>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42257397/

相关文章:

c++ - shared_ptr 赋值符号隐式转换

c++ - 如何更改背景颜色 OnMouseover c++ MFC

c++ - 我怎样才能在 CUDA 中比较很多 vector (有效地)

c++ - vector::clear:内存问题

c++ - 为什么 QString 和 vector<unique_ptr<int>> 在这里显得不兼容?

c++ - 为什么 std::unique_ptr 没有 operator<<?

C++:string.empty() 是否总是等价于 string == ""?

c++ - 如何使用指针修改 vector

c++ - 唯一_Ptr : Attemting To Reference A Deleted Function

c++ - 使用 boost::ref 传递对取值函数的引用