如果没有创建该类的对象,该类的静态成员是否会占用内存?
假设我有一个类,其中有一个静态成员,但我没有创建任何该类型的对象.静态变量会占用内存吗?如果它会被占用,把它放在一个班级里有什么意义?
Say I have a class and I have a static member in it, but I don't create any objects of that type. Will the memory be occupied for the static variable? If it would be occupied, what is the point of putting it in a class?
推荐答案
没有
静态成员不属于类的实例.它们甚至不会增加 1 位实例和类大小!
static members don't belong to the instances of class. they don't increase instances and class size even by 1 bit!
struct A
{
int i;
static int j;
};
struct B
{
int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;
输出:
1
即A
和B
的大小完全一样.静态成员更像是通过 A::j
访问的全局对象.
That is, size of A
and B
is exactly same. static members are more like global objects accessed through A::j
.
在 ideone 上查看演示:http://www.ideone.com/YeYxe
See demonstration at ideone : http://www.ideone.com/YeYxe
$9.4.2/1 来自 C++ 标准 (2003),
$9.4.2/1 from the C++ Standard (2003),
静态数据成员不属于一个类的子对象.有只有一个静态数据成员的副本由所有对象共享类.
$9.4.2/3 和 7 来自标准,
$9.4.2/3 and 7 from the Standard,
一旦静态数据成员被定义,即使没有对象它也存在已经创建了它的类.
静态数据成员被初始化并完全像非本地一样销毁对象 (3.6.2, 3.6.3).
正如我所说,静态成员更像是全局对象!
As I said, static members are more like global objects!
相关文章