c++ - 我可以在 C++11 中使用具有值语义的多态容器吗?

标签 c++ stl c++11

这是 related post 的续集提出了永恒的问题:

Can I have polymorphic containers with value semantics in C++?

问题问得有点不对。它应该更像是:

Can I have STL containers of a base type stored by-value in which the elements exhibit polymorphic behavior?

如果您问的是 C++ 方面的问题,答案是否定的。在某些时候,您将对按值存储的对象进行切片。

现在我再次提出这个问题,但严格按照 C++11。随着语言和标准库的变化,现在是否可以在 STL 容器中按值存储多态对象?

我很清楚在容器中存储指向基类的智能指针的可能性 -- 这不是我要找的,因为我正在尝试构造对象在堆栈上而不使用 new

考虑一下您是否会(从链接的帖子中)作为基本的 C++ 示例:

#include <iostream>

using namespace std;

class Parent
{
    public:
        Parent() : parent_mem(1) {}
        virtual void write() { cout << "Parent: " << parent_mem << endl; }
        int parent_mem;
};

class Child : public Parent
{
    public:
        Child() : child_mem(2) { parent_mem = 2; }
        void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; }

        int child_mem;
};

int main(int, char**)
{
    // I can have a polymorphic container with pointer semantics
    vector<Parent*> pointerVec;

    pointerVec.push_back(new Parent());
    pointerVec.push_back(new Child());

    pointerVec[0]->write();     
    pointerVec[1]->write();     

    // Output:
    //
    // Parent: 1
    // Child: 2, 2

    // But I can't do it with value semantics

    vector<Parent> valueVec;

    valueVec.push_back(Parent());
    valueVec.push_back(Child());        // gets turned into a Parent object :(

    valueVec[0].write();        
    valueVec[1].write();        

    // Output:
    // 
    // Parent: 1
    // Parent: 2

}

最佳答案

您当然不能拥有多态数组(或vector)。数组的元素在内存中连续存储的要求与不同的派生类类型可能具有不同大小的事实根本不兼容。

没有任何标准库容器允许在单个容器中存储不同派生类类型的对象。

关于c++ - 我可以在 C++11 中使用具有值语义的多态容器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3687808/

相关文章:

C++ Windows32 GDI 填充三角形

c++ - 将 argv 复制到新数组中

c++ - 你如何计算 C++ 中文本文件每一行中的单词数?

C++ std::vector<bool> 使用 drmemory 给出未初始化的读取错误

c++ - 使用辅助数组的C++比较器排序

c++ - 可以使用内联命名空间来保持共享库的向后兼容性吗?

c++ - 相关 C++ 类中多态性的最佳实践?

c++ - 根据模板参数选择构造器

c++ - 类似 cplusplus.com 的 C++11 网站

c++ - in(std::cin) :这是什么意思?