静态成员变量如何影响对象大小? [英] How do static member variables affect object size?

查看:78
本文介绍了静态成员变量如何影响对象大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道静态成员变量通常是如何在C ++等语言中实现的,以及它们的使用是否会影响实例化对象的大小。

I'm wondering how static member variables are typically implemented in languages like C++ and if their use affects the size of instantiated objects.

我知道一个静态成员由该类的所有实例共享,但是如何共享?如果它影响对象的大小,那么有10个静态变量会增加大于1的大小吗?

I know that a static members are shared by all instances of that class, but how is it shared? If it affects object size, would having 10 static variables add more size than 1?

我问,因为我可以想到实现它的两种方式:

I'm asking because I can think of two ways it might be implemented:


  • 向每个对象添加指向静态数据的指针,类似于某些实现为虚拟函数表添加指针的方式

  • 静态数据就像全局变量一样直接引用,偏移量由链接器/加载器解析

推荐答案

在C ++中,静态成员不属于类的实例。它们甚至不会增加实例和类的大小,甚至不会增加1位!

In C++, static members don't belong to the instances of class. they don't increase size of instances and class 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),


静态数据成员不属于类的子对象

仅由
类的所有对象共享一个静态数据成员
的一个副本。

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,

$9.4.2/3 and 7 from the Standard,


被定义为
时,即使没有创建该类的对象
也存在。

once the static data member has been defined, it exists even if no objects of its class have been created.

静态数据成员被初始化
并销毁就像非本地
对象(3.6.2、3.6.3)一样。

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

正如我所说,静态成员是更像全局对象!

As I said, static members are more like global objects!

这篇关于静态成员变量如何影响对象大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆