一、背景
Complex* pc = new Complex(1, 2);
String* ps = new String("hello");
...
delete ps;
上面是一個普遍的new 和 delete 語句,到底new是如何實現的呢?
二、原理
2.1New
Complex* pc;
void* mem = operator new( sizeof(Complex) ); // 分配內存
pc = static_cast<Complex*>(mem); // 轉型
pc->Complex::Complex(1, 2); // 構造函數
2.2Delete
String::~String(ps); // 析構函數
operator delete(ps); // 釋放內存
class String
{
public:
~String()
{ delete[] m_data; }
...
private:
char* m_data;
};
注意:
operator new 和 operator delete 是C++裏面一個特殊函數!!!
其先內部調用 malloc(n) 和 free(ps)