본문
Why is the size of an empty class not zero?
To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:
class Empty { };
void f()
{
Empty a, b;
if (&a == &b) cout << "impossible: report error to compiler supplier";
Empty* p1 = new Empty;
Empty* p2 = new Empty;
if (p1 == p2) cout << "impossible: report error to compiler supplier";
}
There is an interesting rule that says that an empty base class need not be represented by a separate byte:
struct X : Empty {
int a;
// ...
};
void f(X* p)
{
void* p1 = p;
void* p2 = &p->a;
if (p1 == p2) cout << "nice: good optimizer";
}
This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".
'번역 > Bjarne Stroustrup's C++ Style and Technique FAQ' 카테고리의 다른 글
Why isn't the destructor called at the end of scope? (2) | 2018.08.13 |
---|---|
How do i define an in class constant? (0) | 2018.08.12 |
Why is "this" not a reference? (0) | 2018.05.10 |
How are C++ objects laid out in memory? (0) | 2018.05.09 |
How do I convert an integer to a string? (0) | 2018.05.09 |
댓글