20230413new-delete使用

87 阅读2分钟

缘起

  • 自己确实对new/delete操作符,不是特别熟,虽然有用过,于是在看智能指针时,觉得要把这部分再给复习一下,没有完全的教材,就自己在网上找了点资料,写了个demo。
  • 还没找到合适的,有体系的教材,或链接,就先整一份,我再寻找,同时后面再整点相关的面试题上去
  • 面试的时候还被问到了vmalloc()kmalloc()的区别

内容

知识框架(lionel,还没整

  • new内置类型(单个变量)、new内置类型(数组形式)
  • operator new

show code

#include<new>
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); //会把整数赋值成5
    cout << *a <<" "<< * b << " " << * c << endl;  //-842150451 0 5

    //char* d = new char("Hello");  //lionel,这种就会报错,引入数组空间

    cout << "2、开辟数组空间,new []的背后发生了啥?" << endl;
    char* p = new char[10];
    char hello[10] = "Hello";
    int result = strncpy_s(p,10,hello,10); //不能直接用p = "Hello"; 【指针p指向字符串的第一个字符】
    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; // 8

    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);  //在栈上使用内存,无需delete
    cout << *pa << " " << *pb << endl; //123 9

    cout << "6、自定义类中使用new" << endl;
    Demo* p6 = nullptr;
    Demo* pDemo = new Demo;
    cout << sizeof(pDemo) <<" " << sizeof(pFoo) << endl;//8 8 【lionel,问题,自定义重载了,也是8啊】

    cout << "最后:delete释放掉" << endl;
    delete a;
    delete b;
    delete c; //c指针本身所占内存空间并未释放

    delete []p;

    delete s;
    delete pDemo;
    delete pFoo;
}
int main() {
    NewDemo();
    return 0;
}

最后

参考链接