C++之new和malloc差别

     在C++程序猿面试中。非常easy被问到new 和 malloc的差别。偶尔在quora上逛。看到Robert Love的总结。才发现自己仅仅知道里面的一两项就沾沾自喜,从来没有像这位大牛一样去细致思考这些问题,借着这篇文章细致探讨下这个经典问题。

一、new是操作符。而malloc是函数
void* malloc(size_t);
void free(void*);
void *operator new (size_t);
void operator delete (void *);
void *operator new[] (size_t);
void operator delete[] (void *);

二、new在调用的时候先分配内存,在调用构造函数。释放的时候调用析构函数。

#include <iostream>
using namespace std;

class Player{
public:
    Player(){
        cout << "call Player::ctor
";
    }

    ~Player(){
        cout << "call Player::dtor
";
    }

    void Log(){
        cout << "i am player
";
    }

};

int main(){
    cout << "Initiate by new
";
    Player* p1 = new Player();
    p1->Log();
    delete p1;

    cout << "Initiate by malloc
";
    Player* p2 = (Player*)malloc(sizeof(Player));
    p2->Log();
    free(p2);
}


输出结果为:

Initiate by new

call Player::ctor

i am player

call Player::dtor

Initiate by malloc

i am player


三、new是类型安全的,malloc返回void*

四、new能够被重载

五、new分配内存更直接和安全

六、malloc 能够被realloc
#include <iostream>
using namespace std;

int main(){
    char* str = (char*)malloc(sizeof(char*) * 6);
    strcpy(str, "hello");
    cout << str << endl;

    str = (char*)realloc(str, sizeof(char*) * 12);
    strcat(str, ",world");
    cout << str << endl;

    free(str);
}

输出结果为:

hello

hello,world

七、new错误发生抛出异常。malloc返回null

八、malloc能够分配随意字节,new 仅仅能分配实例所占内存的整数倍数大小


结论:

学习知识的时候假设能把握整个技术的发展历史和脉络,这样对有些比較难懂的知识就非常easy理解了。

将这些技术放在其所存在的年代,考虑到当时的软硬件环境。能够更好的理解技术本身。

这篇文章是非常浅层次的说明了他们的差别。假设有兴趣能够去研究他们的详细实现。能发现更大的乐趣。

【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/llguanli/p/8492561.html