如何使用std :: aligned_union

Gra*_*rak 9 c++ c++11

在尝试学习如何使用std :: aligned_union时,我无法找到任何示例.我的尝试遇到了一些我不知道如何解决的问题.

struct include
{
    std::string file;
};
struct use
{
    use(const std::string &from, const std::string &to) : from{ from }, to{ to }
    {
    }
    std::string from;
    std::string to;
};
std::aligned_union<sizeof(use), include, use>::type item;
*reinterpret_cast<use*>(&item_) = use{ from, to };
Run Code Online (Sandbox Code Playgroud)

当我尝试在VC++ 2013调试模式下运行程序时,我收到运行时错误memcpy(unsigned char * dst, unsigned char * src, unsigned long count).我假设这是VC++从临时实现赋值的方式.

我如何改变这一点,以便我没有这个问题?

Ker*_* SB 10

aligned_union类型为您提供了适合作为所需类的存储的POD类型 - 它实际上不是该类型的对象.您仍然需要构建自己的对象:

#include <memory>

{
    std::aligned_union<sizeof(use), include, use>::type storage;

    use * p = new (static_cast<void*>(std::addressof(storage))) use(from, to);

    // ...

    p->~use();
}
Run Code Online (Sandbox Code Playgroud)


Cas*_*sey 5

扩展Kerrek的答案:我建议unique_ptr与自定义删除程序一起使用,以自动为您处理破坏。您可以将所有内容很好地包装在工厂中(Rextester现场直播):

struct placement_deleter {
  template <typename T>
  void operator () (T* ptr) const {
    ptr->~T();
  }
};

template <typename T, typename...Args>
std::unique_ptr<T, placement_deleter>
make_in_place(void* place, Args&&...args) {
  return std::unique_ptr<T, placement_deleter>{
    ::new (place) T(std::forward<Args>(args)...)
  };
}

int main() {
  std::aligned_union<0, int, std::string>::type storage;
  {
    auto i = make_in_place<int>(&storage, 42);
    std::cout << *i << '\n';
  }
  {
    auto s = make_in_place<std::string>(&storage, "this is");
    *s += " a test";
    std::cout << *s << '\n';
  }
}
Run Code Online (Sandbox Code Playgroud)