dimanche 1 mai 2016

Why doesn't std::swap work on std::aligned_union

The following code doesn't quite work.

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

for example, it prints chicke boiled without the n. It also hasn't swapped x and y, else it would print boiled chicken.

Aucun commentaire:

Enregistrer un commentaire