理想环节
#include <iostream>
#include <type_traits>
using namespace std;
// Non-trivially-copyable type.
struct NTC
{
int x;
NTC(int mX) : x(mX) { }
~NTC() { cout << "boop." << x << endl; }
};
int main()
{
using AS = aligned_storage_t<sizeof(NTC), alignof(NTC)>;
// Create two `std::aligned_storage` instances
// and "fill" them with two "placement-new-constructed"
// `NTC` instances.
AS as1, as2;
new (&as1) NTC{2};
new (&as2) NTC{5};
// Swap the `aligned_storages`, not their contents.
std::swap(as1, as2);
// Explicitly call `~NTC()` on the contents of the
// aligned storage instances.
NTC& in1{*static_cast<NTC*>(static_cast<void*>(&as1))};
NTC& in2{*static_cast<NTC*>(static_cast<void*>(&as2))};
in1.~NTC();
in2.~NTC();
return 0;
}是上述代码未定义的行为?
下面是我认为正在发生的事情:
NTC是一种不可复制的类型.NTC对象(std::aligned_storage)的内存位置。NTC实例构造到内存位置。NTC对象的析构函数/复制构造函数。我的观点是否有不正确的?如果未定义行为确实发生,那么在程序的哪个部分发生?为什么?
新的潜在更正/错误信息(从删除的答复中收集):
std::aligned_storage几乎只是C样式数组的typedef。std::swap_ranges,它交换数组中的每个元素。std::aligned_storage实例应该交换它们的内容,逐个元素。,我在这些新假设中犯了什么错误吗?
发布于 2015-03-28 14:35:11
在一个不可复制的类型被放入缓冲区后直接访问缓冲区的字节是一个非常糟糕的想法,但还不是没有定义的。
在作为NTC交换后试图访问缓冲区违反了别名规则,basic.lvalp10:
如果程序试图通过除下列类型之一以外的glvalue访问对象的存储值,则行为是未定义的: (10.1) --物体的动态类型, ……
通过memcpy或等效复制一个微不足道的可复制类型是为了保留动态类型。对于不可复制的非琐碎类型,没有这样的含义,所以在交换之后,您就没有任何NTC对象可以访问了。
https://stackoverflow.com/questions/29317981
复制相似问题