C ++动态分配 [英] C++ dynamic allocation

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

问题描述

假设我们有一个班级A

班级A 
{
// blabla
public int x;
}





当我们这样做时:

 A a =新的A(); 



是动态分配的x吗?

解释会很棒。谢谢



我尝试了什么:



我认为是动态完成,因为我们需要抛出对象来访问x。

解决方案

只有非静态成员变量存储在分配的内存块中。在您的示例中,内存仅包含 x 成员,因此至少具有 int 的大小。



您可以通过打印地址来验证这一点:

 A类
{
public:
A(){x = 0; }
int x;
};

int main()
{
A * a = new A();
printf(A的大小=%lu \ n,sizeof(* a));
printf(a =%p \ n的地址,a);
printf(a-> x =%p \ n的地址,& a-> x);
返回0;
}

可能打印

 A的大小= 4 
a的地址= 0x602010
地址a-> x = 0x602010



另请注意我的示例中使用的正确语法(类定义必须以分号结尾, a 是一个指针)。


你可以在堆栈上创建对象,也可以在堆上动态创建。

在堆栈上:



  void  myFunc()
{
A a ;
}





只要执行myFunc,现在就存在a。



动态堆栈:



 A * heapA = new A(); 





现在你有一个指向A的指针,只要你需要它就可以使用它。

之后你需要销毁它才能释放内存:

 delete heapA; 





我希望能回答你的问题。有关详细信息,请参阅内存分配策略 - ModernesCpp.com [ ^


Let's say we have a class A

class A 
{
// blabla
public int x;
}



when we do this:

A a=new A();


is the x also allocated dynamically?
An explanation will be great. Thank you

What I have tried:

I think it is done dynamically since we need to go threw the object to access "x".

解决方案

Only the non-static member variables are stored within the allocated memory block. With your example the memory holds only the x member and has therefore at least the size of an int.

You can verify this by printing out the addresses:

class A
{
public:
    A() { x = 0; }
    int x;
};

int main()
{
    A *a = new A();
    printf("Size of A = %lu\n", sizeof(*a));
    printf("Address of a = %p\n", a);
    printf("Address of a->x = %p\n", &a->x);
    return 0;
}

which might print

Size of A = 4
Address of a = 0x602010
Address of a->x = 0x602010


Note also the correct syntax used in my example (class definition must be terminated with a semicolon and a is a pointer).


You can create object on the stack or dynamically on the heap.
On the stack:

void myFunc()
{
   A a;
}



Now exists the "a" as long as you execute the myFunc.

Dynamically on heap:

A* heapA = new A();



Now you have a pointer to A and can use it as long as you need it.
After that you need to destroy it in order to get the memory free:

delete heapA;



I hope that answers your question. For more details take a look at
Strategies for the Allocation of Memory - ModernesCpp.com[^]


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

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