问题描述
我想知道一个类的大小限制是什么。我做了一个简单的测试:
I was wondering what the size limit for a class is. I did a simple test:
#define CLS(name,other) \
class name\
{\
public: \
name() {};\
other a;\
other b;\
other c;\
other d;\
other e;\
other f;\
other g;\
other h;\
other i;\
other j;\
other k;\
};
class A{
int k;
public:
A(){};
};
CLS(B,A);
CLS(C,B);
CLS(D,C);
CLS(E,D);
CLS(F,E);
CLS(G,F);
CLS(H,G);
CLS(I,H);
CLS(J,I);
无法编译
如果我删除最后声明 - <$ c $
If I remove the final declaration - CLS(J,I);
, it all compiles fine.
这是一个编译器强加的限制,或者它在某处标准?
Is this a compiler-imposed restriction, or is it somewhere in the standard?
推荐答案
在C ++ 11中这是附件B.实现可以施加限制,但是它们应该至少:
In C++11 this is Annex B. Implementations can impose limits, but they should be at least:
- 对象的大小[262 144]。
- 单个类中的数据成员[16 384]。
- 在单个类中声明的成员[4 096]。
一个不直接与你使用的结构类型,我提到它只是因为它表明第二个是确实是总成员,可能包括那些在基地,我不是确定关于成员的成员。
The third one isn't directly relevant to the kind of construction you're using, I mention it just because it indicates that the second one is indeed the total members, presumably including those in bases and I'm not sure about members-of-members. But it's not just about the members listed in a single class definition.
您的实现似乎已经放弃了2 ^ 31个数据成员,或者大小为2 ^ 32,因为它接受 I
,但不接受 J
。显然,编译器拒绝考虑大于 SIZE_MAX
的类,即使程序没有实例化或使用 sizeof
上的类型。因此,即使在编译器方面尽最大努力,我也不会期望在32位实现上工作。
Your implementation appears to have given up either 2^31 data members, or at size 2^32, since it accepts I
but not J
. It's fairly obviously reasonable for a compiler to refuse to consider classes with size greater than SIZE_MAX
, even if the program happens not to instantiate it or use sizeof
on the type. So even with the best possible effort on the part of the compiler I wouldn't ever expect this to work on a 32 bit implementation.
请注意,这些数量只有准则和不确定遵从,因此即使在具有足够的资源来编译使用更大数目的程序的情况下,一致的含义也可以施加任意更小的限制。
Note that "these quantities are only guidelines and do not determine compliance", so a conforming implication can impose an arbitrary smaller limit even where it has sufficient resources to compile a program that uses larger numbers. There's no minimum limit for conformance.
C ++标准中有各种机会,因为合理的实现由于可笑的小资源限制而无用,所以没有额外的危害如果这是另一个。
There are various opportunities in the C++ standard for a conforming implementation to be useless due to ridiculously small resource limits, so there's no additional harm done if this is another one.
C ++ 03是大致相同的:
C++03 is more-or-less the same:
- 对象的大小[262 144]。
- 单个类,结构或联合中的数据成员[16 384]。
- 在单个类中声明的成员[4 096]。
这篇关于类的大小限制是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!