我正在学习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