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

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

问题描述

说我有一个类,我有一个静态成员,但我不创建任何类型的对象。将静态变量占用内存吗?

$ b如果将被占用,将它放入类中有什么意义?

解决方案


$ b

静态成员不属于类的实例。他们不增加实例和类的大小,即使是1位!

  struct A 
{
int一世;
static int j;
};
struct B
{
int i;
};
std :: cout<< (sizeof(A)== sizeof(B))< std :: endl;

输出:

 code> 1 

也就是说, A B 是完全相同的。静态成员更像是通过 A :: j 访问的全局对象。



查看ideone的示范: http://www.ideone.com/YeYxe






$ 9.4.2 / 1来自C ++标准(2003),


静态数据成员不是
类的子对象的一部分。有
只有
类的所有对象共享的静态数据成员
的一个副本。


$ 9.4.2 / 3和7来自标准,




静态数据成员已经被定义,即使没有对象的
被创建。初始化
并完全像非本地
对象(3.6.2,3.6.3)
一样销毁。


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


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?

解决方案

No.

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;

Output:

1

That is, size of A and B is exactly same. static members are more like global objects accessed through A::j.

See demonstration at ideone : http://www.ideone.com/YeYxe


$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 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.

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天全站免登陆