繁体   English   中英

STL容器持有类在该类的声明中

[英]STL container holding class within declaration of that class

我已经用C ++编写了一个用clang ++而不是g ++编译的程序,我想理解为什么。

基本部分是这样的:

class Table {
    private:
        ...
        std::unordered_map<std::string,Table> table_map;
        ...
};

我认为std :: unordered_map将使用“引擎盖下的”指针,因此这是合法的。 我不是在表内部声明表,而是在创建一个容器,该容器在表内部具有指向表的指针。 还是我想。 Clang ++对此没有问题,程序运行正常。

但是,g ++对此note: forward declaration of 'class Table'抱怨,说“ note: forward declaration of 'class Table' ”。 这表明我应该显式地使std :: unordered_map带有指针( std::unordered_map<std::string,Table*>或某种形式的智能指针)。 这需要我做一些额外的工作(而且我正在处理一年多以前编写的代码,因此我不急于要弄清楚我所做的事情才能进行必要的更改)。

这是g ++中的bug,还是clang ++做的聪明的事情实际上不是标准的一部分? 有没有更好的方法可以重写此代码,以便可以在clang ++和g ++上进行编译?

我还有一个名为Value的类,并且Table内有一个值的std :: unordered_map,因此,我将通过创建一个超类元素(Value和Table都从中继承),然后让Table包含std::unordered_map<std::string,Element> 还是因为为元素声明了这样的映射而无法存储值和表?

该错误是由std :: unordered_map必须重新哈希表然后复制元素引起的。 因此,存储在容器中的值必须是完整类型。

您可以通过将值包装到智能指针中来克服它:

#include <iostream>
#include <string>
#include <unordered_map>
#include <memory>           // shared_ptr

class Table {
    private:
    std::unordered_map<std::string, std::shared_ptr<Table> > t;
};

int main() {
    Table t;
    return 0;
}

编译

这是未定义的行为。 除非标准库容器明确声明容器支持它,否则不能使用不完整的类型实例化它(例如, unique_ptr )。

您的选择是:

  • 重新设计您的代码不执行此操作
  • 使用支持此功能的容器库

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM