C++ Placement new 和构造函数调用

标签 c++ operator-keyword allocator

我正在通过以下代码学习新的 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/

相关文章:

C++ 映射分配器将项目存储在 vector 中?

c++ - 如何从 LPWSTR 转换为 'const char*'

c++ - 是否可以在其范围之外访问局部变量的内存?

c++ - 需要类语法解释

memory - Zig Lang 中正确的 BigInt Fibonacci 实现

c++ - STL 的自定义分配器仅在 Release模式下无法编译

c++ - 静态初始化的对象不能放在 try block 中

c++ - 我如何访问通过引用传递给 operator= 函数的对象的私有(private)数据?

c++ - 如何使 SWIG 绑定(bind)类在 Lua 中使用运算符?

c++ - 在 C++ 中存储指向 vector 的指针的类