上课会占用记忆吗? [英] Do classes take memory?

查看:65
本文介绍了上课会占用记忆吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Test
{
    int x;
};
int main()
{
   cout << sizeof(Test) ;
   return 0;
}

输出:4

我只想问一下即使我没有创建任何类的对象测试为什么它打印4?

Output : 4
I just want to ask that even i am not created any object of class Test why it prints 4 ?

推荐答案

sizeof(X) X 创建时采用。调用 new 往往会使用更多的字节来占用内存,但是<$ c的自动存储(堆栈或本地,全局或静态等)数组在实践中,$ c> X [N] 将占用 N * sizeof(X)的内存(由于线程的原因,局部静态函数可能会有点多余)安全要求)。

sizeof(X) is the number of bytes an X takes when created. A call to new tends to use a few more bytes for memory use overhead, but an automatic storage (on-stack or local or global or static etc) array of X[N] will take N*sizeof(X) memory in practice (a little extra maybe for function local statics due to thread safety requirements).

与类型本身占用的内存量无关。

It has nothing to do with the amount of memory the type itself takes.

类如果它们的方法没有进行优化,或者使用了vtable(通过使用 virtual 关键字导致),或者类似方法,它们本身就会使用内存。这样一来,存储代码或虚函数表的内存就可能超出该类实例的内存成本。

Classes themselves use memory if they have methods that are not optimized away, if they have a vtable (caused by use of the virtual keywords), or similar. Then memory storing code or virtual function tables may exist outside of the memory costs of instances of the class.

在C ++语言本身中,无法确定多少类本身需要占用的内存,也没有可靠的方法来确定 new 的开销是多少。通常,您可以通过查看给定平台的运行时行为或编译器或运行时库的代码来解决这个问题。

Within the C++ language itself, there is no way to determine how much memory the class itself takes, nor no reliable way to determine what the new overhead is. You can usually puzzle that out by looking at the runtime behaviour, or the code for the compiler or runtime libraries, for a given platform.

这篇关于上课会占用记忆吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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