我在尝试实现一个类似std::any的容器时遇到了这个问题。
在placement new中使用const是多余的吗?
如果不是,那是什么意思?
我应该在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;
}发布于 2019-07-07 00:09:27
这具有未定义的行为,因为对象是const,并且它被append更改。它在通过malloc值而不是使用new的结果获取指向string的指针时也可能会遇到问题:数组不能与它自己的第一个元素进行指针相互转换,更不用说为其提供存储的对象了(这本身只是一个C++17术语;这是一个活跃的研究领域,因为缺少更好的术语)。
https://stackoverflow.com/questions/56914246
复制相似问题