如果我创建一个这样的类:
// B.h
#ifndef _B_H_
#define _B_H_
class B
{
private:
int x;
int y;
};
#endif // _B_H_
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
// main.cpp
#include <iostream>
#include <vector>
class B; // Forward declaration.
class A
{
public:
A() {
std::cout << v.size() << std::endl;
}
private:
std::vector<B> v;
};
int main()
{
A a;
}
Run Code Online (Sandbox Code Playgroud)
编译时编译器失败main.cpp.现在我知道的解决方案是#include "B.h",但我很好奇为什么它失败了.无论是g++或cl的错误信息都在这个问题很有启发.
给定一个不完整的类型:
struct S;
Run Code Online (Sandbox Code Playgroud)
那么下面的声明是:
S *p; // ok, pointer to incomplete types is allowed
std::deque<S> l; // error, instantiating std::deque with incomplete type is UB
Run Code Online (Sandbox Code Playgroud)
但是下面的声明呢?
std::deque<S> *p; // seems to be UB like the previous case,
// but is it ok if p is not used till S is defined?
std::deque<S*> p; // not really sure about this one
Run Code Online (Sandbox Code Playgroud)
编辑:使用的问题std::list代替std::deque,但这违背了问题的目的,因为std::list明确允许使用不完整的类型。std::deque似乎没有这样的权限。