新的放置取决于 iostream

Placement new depends on iostream

本文关键字:取决于 iostream      更新时间:2023-10-16

为什么放置新取决于#include <iostream>

听起来很荒谬?好吧,此代码仅在注释包含时编译:

// #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’

看起来没有一个候选人是新安置的。好像我的放置新表达式无法识别。除非我包含该标题,这是完全荒谬的,因为它是一种语言功能。

编辑:

这对我来说荒谬,因为我当然已经阅读了有关 cppreference.com 的文档(其中涵盖了放置新内容(,并且列出的标题部门没有。

为什么放置新取决于#include <iostream>

其实不然。新放置取决于<new>。它取决于它,因为语言说它依赖于它。它与运算符新重载有关,这些重载由放置 new 调用并在<new>中声明。

<iostream>恰好为你提供了<new>。当然,你不应该依赖它。