Placement new 取决于 iostream

Placement new depends on iostream

为什么 placement new 取决于 #include <iostream>

听起来很荒谬?好吧,这段代码只有在注释 include:

时才能编译
// #include <iostream>

struct Alignas { void* ptr; };

alignas(Alignas) static char storage[sizeof(Alignas)];

int main() { new(storage) Alignas; }

Gcc 错误(与 Clang 相同):

alignas.cpp:7:27: error: no matching function for call to ‘operator new(sizetype, char [8])’
    7 | int main() { new(storage) Alignas; }
      |                           ^~~~~~~
<built-in>: note: candidate: ‘void* operator new(long unsigned int)’
<built-in>: note:   candidate expects 1 argument, 2 provided
<built-in>: note: candidate: ‘void* operator new(long unsigned int, std::align_val_t)’
<built-in>: note:   no known conversion for argument 2 from ‘char [8]’ to ‘std::align_val_t’

看起来 none 的候选人是新职位。好像我的 placement-new 表达式没有被识别。除非我包括 header,这是完全荒谬的,因为它是一种语言功能。

编辑:

对我来说很荒谬,因为我当然阅读了关于 cppreference.com 的文档(其中涵盖了新的展示位置)和 header列出的部门有 none.

Why does placement new depend on #include <iostream>?

没有。新位置取决于 <new>。它依赖于它,因为语言说它依赖于它。它与 operator new 重载有关,这些重载由 placement new 调用并在 <new>.

中声明

<iostream> 恰好为您添加了 <new>。当然,你不应该依赖它。