类中的静态成员的内存分配 [英] Memory Allocation of Static Members in a Class

查看:137
本文介绍了类中的静态成员的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发布了一个问题:
静态类成员的初始化。

I posted a question recently: Initialization of Static Class members.

现在请检查此代码:

#include<iostream>
class A
{
    static int obj_s;
public: 
    A()
    {
        obj_s++;
        std::cout << A::obj_s << "\nObject(s) Created\n";
    }
};

int A::obj_s = 0;

int main()
{
}

虽然没有创建任何对象的A类,使成员 obj_s 保存一个值 0 - willn'它需要内存,因为它被定义?

Even though one has not created any object of Class A, making the member obj_s hold a value 0 - wouldn't it need memory since its getting defined?

推荐答案

显然,它需要内存。和 int A :: obj_s = 0 是它的作用:它定义的变量及其内存。事实上,当我们定义一个变量 X 时,意味着我们定义一个 sizeof(X)和我们标记为 X 的内存区域。

Obviously, it takes memory. And int A::obj_s=0 is exactly what it does: it defines the variable along with it's memory. In fact, when we say we defined a variable X, that means we define a memory of sizeof(X), and that memory region we label as X.

静态成员:

A :: obj_s 是类的静态成员 A 。和静态成员存在没有任何实例。它们不是 A 实例的一部分。

A::obj_s is a static member of the class A. And static members exist without any instance. They're not part of instances of A.

§9.4.2/ 3和7来自标准,

§9.4.2/3 and 7 from the Standard,


strong>一旦静态数据成员已定义
,即使没有创建其类的
对象,它也存在。

静态数据成员初始化为
并销毁完全类似于非本地
对象(3.6.2,3.6.3)。

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

请阅读我的完整答案:

如果没有创建类的对象,类的静态成员会占用内存吗?

这篇关于类中的静态成员的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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