【发布时间】:2019-07-08 20:51:33
【问题描述】:
以下代码编译良好:
#include <iostream>
#include <memory>
int main()
{
const int * a = new int(5);
std::cout << *a << std::endl; // Prints 5
// *a = 5; // Compiler error.
using at = std::allocator_traits<typename std::allocator<int>>;
auto alloc = std::allocator<int>();
at::construct(alloc, a);
std::cout << *a << std::endl; // Prints 0
}
在底层 libstdc++ 确实
::new((void*)a) int;
但是a 是const!
这是未定义的行为吗?或者安置新的不算作修改?
我修改了*a的值,即const。据我了解,这是不允许的:
通过非常量访问路径修改 const 对象和 通过非易失性左值结果引用易失性对象 在未定义的行为中。
【问题讨论】:
-
这看起来像是一个合理的骗局:stackoverflow.com/questions/42997440/…。不是 100% 确定,所以我会让你/社区来决定。
-
@NathanOliver:太好了!谢谢你。通过它阅读。
-
@NathanOliver 在初始化内存上使用placement-new是否合法似乎只是问题的一部分。
std::allocator_traits::construct()是否合法是另一部分。
标签: c++ c++11 c++14 language-lawyer allocator