new和malloc的区别

一、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\n";
    }

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

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

};

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

    cout << "Initiate by malloc\n";
    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 只能分配实例所占内存的整数倍数大小

 

posted @ 2016-06-27 13:55  不止所见  阅读(5527)  评论(0编辑  收藏  举报