zoukankan      html  css  js  c++  java
  • C++之new和malloc区别

         在C++程序员面试中,很容易被问到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 只能分配实例所占内存的整数倍数大小


    结论:

    学习知识的时候如果能把握整个技术的发展历史和脉络,这样对有些比较难懂的知识就很容易理解了。将这些技术放在其所存在的年代,考虑到当时的软硬件环境,可以更好的理解技术本身。这篇文章是很浅层次的说明了他们的区别,如果有兴趣可以去研究他们的具体实现,能发现更大的乐趣。

  • 相关阅读:
    Bit Manipulation
    218. The Skyline Problem
    Template : Two Pointers & Hash -> String process
    239. Sliding Window Maximum
    159. Longest Substring with At Most Two Distinct Characters
    3. Longest Substring Without Repeating Characters
    137. Single Number II
    142. Linked List Cycle II
    41. First Missing Positive
    260. Single Number III
  • 原文地址:https://www.cnblogs.com/fengju/p/6174292.html
Copyright © 2011-2022 走看看