对象分配内存的位置 [英] Where Objects Allocate the memory

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

问题描述

朋友们!

我想知道:
当我们声明一个类的对象时,该类的对象将分配多少内存.

例如:

Hi friends!

I want to know that:
When we declare the objects of an class,where an how much memory will be allocated by object of that class.

Ex:

class A
{
  public : display()
  {
  int v = 10;
  cout<<"\nv:"<<v;
  }
}
main()
{

A  a1;  //hw much & where a1 allocates memmory.
A *aptr;//hw much & where a1 allocates memmory.

getch();
}

推荐答案

多少内存"由sizeof运算符 [ ^ ].

以下程序的易于编译的版本
''How much memory'' is given by sizeof operator[^].

The following, compiler-friendly version of your program
class A
{
  public :
  void display()
  {
    int v = 10;
    std::cout<<"\nv:"<<v;
  }
};
int main()
{
  A  a1;  //hw much & where a1 allocates memmory.
  A *aptr;//hw much & where a1 allocates memmory.
  std::cout << "sizeof(a1)= " << sizeof(a1) << std::endl;
  std::cout << "sizeof(aptr)= " << sizeof(aptr) << std::endl;
}



产生以下输出:



produces the output below:

sizeof(a1)= 1
sizeof(aptr)= 4



我们得到sizeof(a1)=1是因为该类为空(即没有数据),但是无论如何C++对象必须具有size > 0(必须具有标识,请参见 [指向对象的指针"(指向垃圾),并且指针的宽度为4个字节.我的32位系统.


两种分配都在堆栈上进行.
:)



We get sizeof(a1)=1 because the class is empty (i.e. has no data), but, anyway a C++ object must have size > 0 (must have an identity, see Stroustrup''s "Why is the size of an empty class not zero?"[^]).

We get sizeof(aptr)=4 because the program doesn''t allocate an object, it allocates just ''a pointer to an object'' (pointing to garbage) and pointers are 4-bytes wide on my 32-bits system.


Both allocations happens on the stack.
:)


//A a1;
+内存在堆栈上= sizeof(A)
+堆上内存,动态分配
->通过类构造函数(可选)
->由类内嵌对象的类构造函数(可选)
->通过派生A的类(可选)

//A * aptr;
+内存在堆栈上= sizeof(INT_PTR)

//A * aptr = new A;
+容纳aptr的内存在堆栈中sizeof(INT_PTR)
+堆上内存,已动态分配= sizeof(A)
->通过类构造函数(可选)
->由类内嵌对象的类构造函数(可选)
->根据派生A的类(可选)


:)
// A a1;
+ The memory is on-stack =sizeof(A)
+ The on-heap memory, allocated dynamically
-> by the class constructor (optional)
-> by the class constructors of the in-class embedded objects (optional)
-> by the classes from which A is derived (optional)

// A* aptr;
+ The memory is on-stack =sizeof(INT_PTR)

// A* aptr = new A;
+ The memory that holds aptr is on-stack sizeof(INT_PTR)
+ The on-heap memory, allocated dynamically=sizeof(A)
-> by the class constructor (optional)
-> by the class constructors of the in-class embedded objects (optional)
-> by the classes from which A is derived (optional)


:)


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

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