【发布时间】:2020-06-26 12:22:45
【问题描述】:
为什么新展示位置依赖于#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’
看起来没有一个候选人是新职位。好像我的placement-new 表达式无法识别。除非我包含那个完全荒谬的标题,因为它是一种语言功能。
编辑:
这 对我来说很荒谬,因为我当然已经阅读了 cppreference.com 上的文档(其中涵盖了新的展示位置),并且没有列出的标题部门。
【问题讨论】:
-
它可能实际上并不依赖于
<iostream>。它可能取决于您的<iostream>实现碰巧包含的另一个标头。编辑:可能是<new>. -
它可能需要
#include <new>,但我找不到引用。 “这完全是荒谬的,因为它是一种语言特性” 依赖于标准标题的语言特性并不新鲜,请参阅typeid、std::initializer_list... -
正如 HolyBlackCat 提到的,它是
<new>的一部分。您可以从标准中看到[new.syn]中的函数定义。 -
Placement new 是一种将额外参数传递给
operator new的通用机制。您正在谈论的是标准库使用placement new 在给定位置构造对象。这取决于头文件<new>,但新放置通常不需要头文件。
标签: c++ memory-alignment placement-new