我想知道静态成员变量通常如何在 C++ 等语言中实现,以及它们的使用是否会影响实例化对象的大小。
我知道静态成员由该类的所有实例共享,但它是如何共享的?如果它影响对象大小,那么拥有 10 个静态变量会增加比 1 更多的大小吗?
我之所以这么问,是因为我可以想到两种可能的实现方式:
- 向每个对象添加指向静态数据的指针,类似于某些实现添加指向虚函数表的指针的方式
- 静态数据只是像全局变量一样被直接引用,偏移量由链接器/加载器解析
最佳答案
在 C++ 中,静态成员不属于类的实例。它们甚至不会增加实例和类的大小 1 位!
struct A
{
int i;
static int j;
};
struct B
{
int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;
输出:
1
即A
和B
的大小完全相同。静态成员更像是通过 A::j
访问的全局对象。
在 ideone 上查看演示:http://www.ideone.com/YeYxe
$9.4.2/1 来自 C++ 标准 (2003),
A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the objects of the class.
标准版 9.4.2/3 美元和 7 美元,
once the static data member has been defined, it exists even if no objects of its class have been created.
Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).
正如我所说,静态成员更像是全局对象!
关于c++ - 静态成员变量如何影响对象大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640989/