c++ - 为什么 std::swap 不能在 std::aligned_union 上工作

标签 c++ c++11

以下代码无法正常工作。

#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;
}

例如,它打印 chicke boiled 而没有 n。它也没有交换 xy,否则它会打印 boiled chicken

最佳答案

这不可能。交换的正确行为需要知道 union 包含哪种类型。这不是一个有区别的 union ,因此任何依赖于知道 union 包含哪种类型的操作都将失败,除非特别提供该信息。

我很想听听您认为这会如何运作,甚至是可以想象的。您认为 std::swap 有什么魔力?

关于c++ - 为什么 std::swap 不能在 std::aligned_union 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965533/

相关文章:

php - 将 PHP 中的 $_POST 变量传递给由 exec() 函数运行的 C++ 程序

c++ - 使用 boost-spirit 解析简单的 csv 表

c++ - 如何使一个函数的返回类型与另一个函数的返回类型相同?

c++ - 使用 `Node*` 作为列表的迭代器

multithreading - 当有一个读者和一个作者线程时,我是否需要使用 std::atomic_

c++实现时钟来测量执行时间

C++ 在尝试比较字符串 "=="或 CString.Find() 时什么更好

c++ - 对共享的 std::unordered_map 线程只写是否安全?

c++ - 错误 : 'A' is an inaccessible base of 'B'

c++ - 返回对字符串数组的引用