我正在尝试重载new运算符以分配自己的内存,但是我仍然需要构造该对象。
这就是为什么我决定通过可变参数模板传递参数,以便正确地输入对象的构造函数。

在此示例中,构造函数被调用了两次,我无法解释原因。
似乎重载的新函数会自动调用构造函数。

#include <stdlib.h>
#include <iostream>
#include <new>

class A
{
public:
  template<typename... Args>
  void *operator new(size_t sz, Args ...parameters)
  {
    void *mem = ::operator new(sizeof(A));
    A *var = ::new (mem) A(parameters...);
    return var;
  }
  A() : num(0) { std::cout << "Default" << std::endl; }
  A(int nb) : num(nb) { std::cout << "Integer = " << num << std::endl; }
  const int num;
};

int main()
{
  A *obj = new A(3);
  std::cout << "Obj result = " << obj->num << std::endl;
}

最佳答案

已修复,没有理由尝试在重载内调用构造函数,该对象将在返回的void *的指针分配的内存中构造。

关于c++ - C++:重载的New调用会自动构造对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32402842/

10-14 16:47
查看更多