我正在通过以下代码学习新的 C++ 布局。
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
的启动。但是为什么在那之后我得到了两个“默认构造函数”?我是否遗漏了有关新展示位置的信息?另外,我如何使用第二个接受输入整数的非默认构造函数来实现新的放置?
最佳答案
new (&global_cell) Cell
在您的 operator new
重载中是一个默认构造,main
中的 new Cell
是另一个。
operator new
只应该分配内存,而不是构造对象;之后会自动调用相关的构造函数。
在非默认构造函数中使用 placement new 并不是很复杂:
new (&global_cell) Cell(2)
(也就是说,与“常规”new
没有区别。)
关于C++ Placement new 和构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301508/