为什么 std::swap 不适用于 std::aligned_union
Why doesn't std::swap work on std::aligned_union
以下代码不太适用。
#include <type_traits>
#include <string>
#include <iostream>
template<std::size_t Len, class... Types>
using dataType = typename std::aligned_union<Len,Types...>::type;
int main()
{
dataType<1,int,float,std::string,char,bool> x;
dataType<1,int,float,std::string,char,bool> y;
new (&x) std::string("chicken");
new (&y) std::string("boiled");
std::swap(x,y);
std::cout << *reinterpret_cast<std::string*>(&x) << " " << *reinterpret_cast<std::string*>(&y) << std::endl;
}
例如它打印没有n
的chicke boiled
。它也没有交换x
和y
,否则它将打印boiled chicken
。
这不可能工作。交换的正确行为需要知道联合包含哪种类型。这不是一个有区别的并集,因此任何依赖于知道并集包含的类型的操作都将失败,除非专门提供了该信息。
我很想听听你是怎么想的,甚至可以想象。你认为std::swap
有什么魔力?
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 使用std::函数映射对象方法
- 为什么对Aligned STD ::数组的初始自动矢量载荷是标量?(g /clang )