C++中new/malloc/free/delete的区别

2020-01-01  本文已影响0人  突击手平头哥

C++中new/malloc/free/delete的区别

共同点

区别

int main()
{
    int *a = new int;
    int *b = (int*)malloc(sizeof(int));
    delete a;
    free(b);
}
#include <iostream>     // std::cout
#include <new>          // std::bad_alloc
 
int main()
{
    char *p;
    try
    {
        do
        {
            p = new char[2047 * 1024 * 1024];         //每次1M
        } while (p);
    }
    catch(std::exception &e)
    {
        std::cout << e.what() << endl;
    };
 
    return 0;
}

//结果
std::bad_alloc

new返回NULL指针

#include <iostream>     // std::cout
#include <new>          // std::bad_alloc
 
int main()
{
    char *p = new (std::nothrow) char[2047 * 1024 * 1024];         //每次1M
    if(!p)
    {
        std::cout<<"alloc error"<<std::endl;
    }
 
    return 0;
}

使用std::nothrow

上一篇 下一篇

猜你喜欢

热点阅读