new就是一个operator,像+-=*/一样(可以编译器右键查看其定义看出)
也就是可以overload这个operator并改变它的功能
展示new在代码中创建变量:
#include <iostream>
#include<string>
//这里采用这种方法可以重新定义修改关键字
using String = std::string;
class Entity
{
private:
String m_Name;
public:
Entity() { m_Name = "void_name"; }
Entity(std::string name) :m_Name(name) {}
//这里加上const关键字,防止变量被修改的可能性
std::string Getname() const { return m_Name; }
};
int main()
{
int a = 2;
//当使用new关键字时候,不会把存变量的内存放到free list中
int* b = new int;//初始化int变量,4bytes
int* c = new int[50]; //初始化int的array list,200 bytes
//这种new创建的要带方括号 delete[] c
Entity* d = new Entity;
Entity* e = new Entity[20];//这样会在内存空间上分配50乘以指定string变量的空间
//下面这两句本质是相同的
Entity* f = new Entity();//如果以这种方式创建,就不仅仅是分配内存空间,同时有调用constructor(构造器)
Entity* g = (Entity*)malloc(sizeof(Entity));//但是这一句只分配内存,不会调用constructor
//使用完new关键字,要进行内存释放:scope space pointer、reference counting
delete b;
std::cin.get();
}
- void* 空指针,本质就是一个内存地址(只考虑会被分配多少)
- 内存分配基础状态函数malloc:获取size多少bytes想要,然后返回一个void*
placement new:https://blog.csdn.net/zhangxinrun/article/details/5940019