指向向量和多态的唯一指针 [英] Unique pointer to vector and polymorphism

查看:54
本文介绍了指向向量和多态的唯一指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,我想创建指向基础对象向量的唯一指针.我想保留在Base( SubClass )的向量子类中,但是由于基本类是虚拟的,因此我在初始化时遇到问题.

I have problem, I want to create unique pointer to vector of Base objects. I want keep in this vector subclass of Base (SubClass), but i have problem with initialization, because Base class is virtual.

std::unique_ptr<std::vector<Base>> baseVector = std::make_unique<std::vector<Base>>();
SubClass newObject();
baseVector->push_back(newObject);

推荐答案

简短版本:您不希望动态指针指向 Base 的集合;您需要一个动态指向 Base 的指针.

Short Version: You don't want a dynamic pointer to a collection of Base; you want a collection of dynamic pointer-to-Base.

您似乎误解了将 std :: unique_ptr 放置在多态集合中的何处.并不是集合需要成为多态性起作用的指针.是里面的物体.

You seem to be misunderstanding where to place std::unique_ptr in your polymorphic collection. It isn't the collection that needs to be pointers for polymorphism to work; it's the object held within.

例如:

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

struct Base
{
    virtual ~Base() {}

    virtual void foo() const = 0;
};

class DerivedOne : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "DerivedOne\n";
    }
};

class DerivedTwo : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "DerivedTwo\n";
    }
};

int main()
{
    std::vector< std::unique_ptr<Base> > objs;

    objs.emplace_back(std::make_unique<DerivedOne>());
    objs.emplace_back(std::make_unique<DerivedTwo>());

    // via operator[]
    objs[0]->foo();
    objs[1]->foo();

    // via range-for
    for (auto const& p : objs)
        p->foo();

    // via iterators
    for (auto it = objs.begin(); it !=objs.end(); ++it)
        (*it)->foo();
}

输出

DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
DerivedOne
DerivedTwo

是否要通过智能指针动态管理集合本身与该问题无关(并且有些可疑).

Whether you want the collection itself to be managed dynamically via a smart pointer is unrelated (and somewhat questionable) to this issue.

这篇关于指向向量和多态的唯一指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆