"new operator" 将另一个 class 实例化为工厂?

"new operator" to instantiate another class as a factory?

我尝试使用 new 运算符来实例化特定的 class 而不是 new 关键字后面的那个。

我尝试为摘要 class 提供一种 "factory"。

在我看来这是不可能的,但让我们仔细检查一下! 这段代码可以编译,但主要代码将其视为 Test(而不是 TestImpl class)

class Test
{
public:
  virtual int testCall() { return 0; };

  static void* operator new(std::size_t);
};

class TestImpl : public Test
{
  virtual int testCall() override
  {
    return i;
  }

  int i = 15;
};

void* Test::operator new(size_t sz)
{
  return ::new TestImpl();
}

void main()
{
  Test * t = new Test(); // Call the new operator, correctly
  int i = test->testCall(); // i == 0 and not 15
}

请注意,对于每个 new expression,将执行以下两件事:

  1. 通过适当的operator new分配内存。
  2. 在步骤#1 分配的内存上构造对象。

所以operator new只分配内存,不构造对象。这意味着,对于 Test * t = new Test();,仍然会在重载的 operator new 分配的内存上构造一个 Test;即使你在 operator new 中构建了一个 TestImpl,但在 operator new 完成后,它很快就会在同一内存中被覆盖。