无法在std :: map成员变量中分配具有正向声明值的类 [英] Can't allocate class with forward declared value in std::map member variable

查看:104
本文介绍了无法在std :: map成员变量中分配具有正向声明值的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

test.h

#ifndef TEST_H
#define TEST_H

#include <map>
struct Incomplete;

class Test {
     std::map<int, Incomplete> member;
public:
    Test();
    int foo() { return 0; }
};

#endif

test.cpp

#include "test.h"
struct Incomplete {};
Test::Test() {}

main中。 cpp

#include "test.h"

int main() {
    Test test;
    return test.foo();
}

g ++ 4.7给我一个错误,指出 struct Incomplete 在我编写 g ++ main.cpp test.h -o main.o 时被向前声明。

g++ 4.7 gives me an error that struct Incomplete is forward declared when I write g++ main.cpp test.h -o main.o.

但是,如果更改 std :: map< int,Incomplete>成员 std :: map< int,Incomplete *>成员 main.o 进行编译。为什么是这样?

However, if I change std::map<int, Incomplete> member to std::map<int, Incomplete*> member, main.o compiles. Why is this?

推荐答案


这是为什么?

Why is this?

因为未定义C ++标准库容器以使用不完整的成员类型。 这是设计使然 1 –但这可以说是一个错误(在将来的C ++版本中可能会更改)。 Boost.Containers 库对此进行了修复。

Because the C++ standard library containers are not defined to work with incomplete member types. This is by design1 – but it’s arguably an error (and might be changed in future versions of C++). The Boost.Containers library fixes this.

您的带指针代码可以工作,因为指向不完整类型的指针本身就是完整类型。但是,这显然会极大地改变您类型的语义(特别是谁来管理内存?),通常不建议使用它来代替。

Your code with pointers works because a pointer to an incomplete type is itself a complete type. However, this obviously changes the semantics of your type quite drastically (in particular, who manages the memory?) and it’s generally not a good idea to use this as a replacement.

1 值得指出的是,本文声称您在技术上不能实施 std :: map 使用不完整的类型。但是,这种说法是错误的。

1 It’s worth pointing out that the article claims that you technically cannot implement std::map to work with incomplete types. However, this claim is wrong.

这篇关于无法在std :: map成员变量中分配具有正向声明值的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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