指向向量和多态性的唯一指针

Unique pointer to vector and polymorphism(指向向量和多态性的唯一指针)
本文介绍了指向向量和多态性的唯一指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,我想创建指向 Base 对象向量的唯一指针.我想保留 Base 的这个向量子类(SubClass),但是初始化有问题,因为 Base 类是虚拟的.

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
";
    }
};

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

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Polymorphic copy-constructor with type conversion(具有类型转换的多态复制构造函数)
Cast to a Child(铸造给孩子)
How to use virtual functions to achieve a polymorphic behavior in C++?(如何使用虚函数在 C++ 中实现多态行为?)
Polymorphism is not working with function return values of same data type (Base and Inherited class)(多态性不适用于相同数据类型(基类和继承类)的函数返回值)
Size of class with virtual function adds extra 4 bytes(具有虚函数的类的大小增加了额外的 4 个字节)
Right design pattern to deal with polymorphic collections of objects(正确的设计模式来处理对象的多态集合)