在上一章笔记中我们用到了在堆上初始化对象。
#include <iostream>
#include <string>
class Entity
{
private:
std::string m_name;
public:
Entity():m_name("nothing"){}
Entity (const std::string& name):m_name(name){}
const std::string& GetName()const
{
return m_name;
}
};
int main()
{
int a = 2;
int* a = new int[50];
Entity* e1 = new Entity("shaojie");
std::cout<<(*e1).GetName()<<std::endl;
delete e1;
std::cin.get();
}
我们关心main函数中int a = 2;在栈上对a赋值为2,再分配1MB或者2MB的数据时大小都没有什么问题。特点就是函数花括号结束 a就立刻释放。
int* a = new int[50]
int*因为new返回的是指针,new意味着找到一处4*50字节的内存并返回其地址给a。堆上分配有更大的内存空间,并且不受花括号作用域的影响。
在c语言中malloc表示对函数分配内存,以下两行近似等效。计算大小再分配内存再返回指针。
Entity* e1 = new Entity("shaojie");
Entity* e1 = (Entity*)malloc(sizeof(Entity));
有什么区别呢?new里我们调用了Entity(),我们在完成以上功能时,还调用了Entity构造函数。这就是他们的区别。