如果没有创建该类的对象,该类的静态成员是否会占用内存? [英] Do static members of a class occupy memory if no object of that class is created?

查看:24
本文介绍了如果没有创建该类的对象,该类的静态成员是否会占用内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类,其中有一个静态成员,但我没有创建任何该类型的对象.静态变量会占用内存吗?如果它会被占用,把它放在一个班级里有什么意义?

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

AB的大小完全一样.静态成员更像是通过 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!

这篇关于如果没有创建该类的对象,该类的静态成员是否会占用内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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