Why is the size of an empty class not zero?
2007-02-11 08:42
495 查看
To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:
There is an interesting rule that says that an empty base class need not be represented by a separate byte:
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".
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".
相关文章推荐
- Why is the size of an empty class not zero?
- Why is the size of an empty class not zero?
- Why is the size of an empty class not zero in C++?
- Why is the size of an empty class not zero in C++?
- Incorrect decrement of the reference count of an object that is not owned at this point by the calle
- kdbchk: the amount of space used is not equal to block size
- Bean property 'RegDao' is not writable or has an invalid setter method. Does the parameter type of t
- 异常笔记(2)--object is not an instance of declaring class while invoking public abstract java.lang.Long
- object is not an instance of declaring class 反射异常
- java反射错误:object is not an instance of declaring class
- Question 30: What is the order of destructor calls for an object of class Y inherited from class X that has an object of class A
- 使用MagicAJax的AjaxPanel时有时会弹出"Using the AjaxCallHelper write methods outside of an AjaxCall is not allowed."
- Why the description of Page Layout is not showing
- 报错:object is not an instance of declaring class
- java.lang.IllegalArgumentException: object is not an instance of declaring class
- Why is the maximum size of the Java heap fixed?
- HIbernate 3.2 java.lang.IllegalArgumentException: object is not an instance of declaring class
- [Repaste] Why Dart is not the language of the future
- 项目启动后,访问报 object is not an instance of declaring class 错误
- mysql5.7.12/13在安装新实例时报错:InnoDB: auto-extending data file ./ibdata1 is of a different size 640 pages (rounded down to MB) than specified in the .cnf file: initial 768 pages, max 0 (relevant if non-zero