使用两个参数但不赋值调用 new 运算符

Calling the new operator with two arguments but without assignment

我找到了这段代码,但我不明白为什么它在项目中有效。代码结构为:

class MyClass {
    int value;
};

struct MyStruct {
    MyClass classA;
    MyClass classB;
};

int main() {

    MyStruct myStruct;

    new (&((&myStruct)->classA)) MyClass();
    new (&((&myStruct)->classB)) MyClass();
}

(内部的 & 号是我添加的,用于创建一个较小的示例。在源代码中,myStruct 是一个指针)。

编译器说

In function int main()
error: no matching function for call to ‘operator new(sizetype, MyClass*)’
    new (&((&myStruct)->classA)) MyClass();
                                         ^
note: candidates are:
note: void* operator new(long unsigned int)
note:   candidate expects 1 argument, 2 provided

也许我遗漏了一些重要的东西。这是一个大项目,我无法复制它。我无法创建 MWE。我希望有人能向我解释这段代码背后的主要思想以及我必须更改哪些内容才能编译它。

Placement new 是 C++ 语言功能之一,需要先包含适当的 header,然后才能尝试使用它们。

使用 placement new 时,表达式必须调用 operator new 的重载作为其计算的一部分。 这个 重载,确切地说:

void* operator new (std::size, void*);

但并不是每个翻译单元都会自动为您声明此功能。因此,要将其拉入,您必须包含正确的 header (<new>).


附带说明一下,您显示的代码非常糟糕。它构造了myStruct两次的成员! non-trivial 案例可能会造成严重破坏。

非常明确地初始化 myStruct 的正确方法是这样的:

MyStruct myStruct {
  {}, // Default construct classA
  {}  // Default construct classB
};