Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Khác biệt new/delete vs malloc/free trong C++

new / delete (C++ Operator)

  • Là toán tử (operator), không phải hàm
  • Tự động gọi constructor khi cấp phát, destructor khi giải phóng
  • Trả về con trỏ đúng kiểu (không cần cast)
  • Ném std::bad_alloc khi thất bại (không trả NULL)
  • Có thể overload tùy chỉnh

Cú pháp

// Đơn lẻ
Type* ptr = new Type;           // Không khởi tạo
Type* ptr = new Type();         // Value-initialized (0/null)
Type* ptr = new Type(args);     // Constructor có tham số

// Mảng
Type* arr = new Type[n];        // Mảng n phần tử
delete[] arr;                   // PHẢI dùng delete[] cho mảng

Ví dụ new/delete

#include <iostream>
using namespace std;

class MyClass {
    int id;
public:
    MyClass(int i) : id(i) { cout << "Construct " << id << endl; }
    ~MyClass() { cout << "Destroy " << id << endl; }
};

int main() {
    int* p1 = new int;           // int đơn
    *p1 = 28;
    
    float* p2 = new float(299.121f); // Khởi tạo giá trị
    
    MyClass* arr = new MyClass[3];   // Mảng 3 object
    
    cout << "Values: " << *p1 << " " << *p2 << endl;
    
    delete p1;
    delete p2;
    delete[] arr; // Gọi destructor cho 3 object
    return 0;
}

Kết quả

Construct 0
Construct 1
Construct 2
Values: 28 299.121
Destroy 2
Destroy 1
Destroy 0

malloc / free (C Library Functions)

  • Là hàm thư viện C (<stdlib.h> / <cstdlib>)
  • Chỉ cấp phát byte thô, không gọi constructor/destructor
  • Trả về void* - cần cast trong C++
  • Trả về NULL khi thất bại
  • Không thể overload

Cú pháp

void* ptr = malloc(size_t size);
free(ptr);

Bảng so sánh chi tiết

Đặc điểmnew/deletemalloc/free
Gọi constructorCóKhông
Gọi destructorCó (delete)Không
Kiểu trả vềType* (type-safe)void* (cần cast)
Thất bạiThrow bad_allocTrả NULL
OverloadCó (global/class)Không
Mảngnew[] / delete[]malloc(size*count)
ReallocKhông córealloc()
Placement newCóKhông

Khi nào dùng cái nào?

  • new/delete: Code C++ hiện đại, object có constructor/destructor, RAII
  • malloc/free: Tương thích C, cấp phát byte thô, cần realloc, memory pool custom
  • Best practice C++11+: std::make_unique, std::make_shared, std::vector, std::string - tránh new/delete thủ công

Placement new (Nâng cao)

// Cấp phát bộ nhớ thô
void* buffer = malloc(sizeof(MyClass));

// Gọi constructor tại vị trí đã cấp phát (placement new)
MyClass* obj = new (buffer) MyClass(42);

// Gọi destructor thủ công
obj->~MyClass();

// Giải phóng buffer
free(buffer);