缘起
- 自己确实对
new/delete操作符,不是特别熟,虽然有用过,于是在看智能指针时,觉得要把这部分再给复习一下,没有完全的教材,就自己在网上找了点资料,写了个demo。
- 还没找到合适的,有体系的教材,或链接,就先整一份,我再寻找,同时后面再整点相关的面试题上去
- 面试的时候还被问到了
vmalloc()和kmalloc()的区别
内容
知识框架(lionel,还没整)
- new内置类型(单个变量)、new内置类型(数组形式)
operator new
show code
class Foo {
public:
void* operator new(std::size_t size) {
cout << " Foo :: operator new" << endl
return malloc(size)
}
}
void NewDemo() {
class Demo{}
cout<<"1、开辟单变量存储空间"<<endl
int* a = new int
int *b = new int()
int* c = new int(5)
cout << *a <<" "<< * b << " " << * c << endl
//char* d = new char("Hello")
cout << "2、开辟数组空间,new []的背后发生了啥?" << endl
char* p = new char[10]
char hello[10] = "Hello"
int result = strncpy_s(p,10,hello,10)
cout << p << endl
//问题1:多维数组的返回值类型?https://blog.csdn.net/xiaomingZeng/article/details/77949822
cout << "3、new作为运算符,在堆上分配内存,自动调用类的构造函数" << endl
string* s = new string("test new string")
cout << *s << endl
cout << "4、new作为函数,即 运算符重载 operator new, void *operator new(size_t size)" << endl
Foo* pFoo = new Foo
cout << sizeof(pFoo) << endl
cout << "5、placement new在已存在的内存上分配一个对象, new(buffer) type(size_t size)" << endl
//void *operator new(size_t, void *buffer) {return buffer
char str[22]
int data = 123
int* pa = new(&data)int
int* pb = new(str) int(9)
cout << *pa << " " << *pb << endl
cout << "6、自定义类中使用new" << endl
Demo* p6 = nullptr
Demo* pDemo = new Demo
cout << sizeof(pDemo) <<" " << sizeof(pFoo) << endl
cout << "最后:delete释放掉" << endl
delete a
delete b
delete c
delete []p
delete s
delete pDemo
delete pFoo
}
int main() {
NewDemo()
return 0
}
最后
参考链接