我正在學習C++放置新的代碼。C++ Placement new and構造函數調用
class Cell {
public:
Cell() {
printf("default constructor by %s\n", __func__);
}
Cell(int ina) : a(ina) {
printf("customized constructor.\n");
}
~Cell() {}
void* operator new(size_t); // Operator new.
void* operator new(size_t, Cell*p) {
return p;
}
private:
int a; // tmp variable.
};
// Global variable.
Cell global_cell;
void* Cell::operator new(size_t size) {
printf("start running the placement new\n");
Cell* ptr = new (&global_cell) Cell;
printf("the cell pointer is %p and the global address is %p\n", ptr, &global_cell);
return ptr;
}
int main() {
printf("====\n");
Cell *ptr = new Cell;
printf("====\n");
}
這是我得到的輸出:
default constructor by Cell
=====
start running the placement new
default constructor by Cell
the cell pointer is 0x60107c and the global address is 0x60107c
default constructor by Cell
=====
我所知道的第一個「默認構造函數」來源於global_cell
開始。但爲什麼在那之後我得到了兩個「默認構造函數」?我錯過了關於展示位置的新內容嗎?另外,我怎樣才能實現與第二個非默認的構造函數接受一個輸入整數的位置?
對不起,這是一個錯字,當我嘗試手動編輯帖子。 – Jes