【发布时间】:2019-07-06 12:50:27
【问题描述】:
我在尝试实现 std::any 之类的容器时遇到了这个问题。
const 在placement new 中的使用是多余的吗?
如果不是,那是什么意思?
我应该在placement new 上使用std::decay 吗?
#include <iostream>
int
main() {
auto * address = std::malloc(sizeof(std::string));
// What does `const` means here?
// Is it superfluous?
// Is `std::decay` needed here too?
new (address) std::string const("hello, world");
// Is this undefined behaviour?
// In the context of my code: T -> std::decay<T>
// Here I'm just using a `std::string` as an example
auto & str = *static_cast<std::string *>(address);
str.append("hi");
std::cout << str << '\n';
return 0;
}
【问题讨论】:
-
你不需要它。只需使用
new (address) std::string{"hello world"};。 -
理论上,分配只读内存是有效的。实际上,没有人分配他们无法写入的内存。所以
constin new 是没用的——如果它真的有效的话。 -
Davis weites 是 UB。如果你尝试强制转换 new 返回的指针,编译器会告诉你你正在尝试做一些非法的事情。
标签: c++ constants placement-new