代码之家  ›  专栏  ›  技术社区  ›  DarthRubik

我能隐式创建一个普通的可复制类型吗

  •  1
  • DarthRubik  · 技术社区  · 6 年前

    我的问题是:

    假设类型 T 是可复制的…可以“创建”此类型的实例而不调用构造函数…就像这样:

    #include <type_traits>
    #include <cstring>
    
    using T = int; // T can be any trivially copyable type
    
    
    T create(const T& other)
    {
        std::aligned_storage_t<sizeof(T),alignof(T)> my_T;
    
        std::memcpy(&my_T,&other,sizeof(T));
    
        return *reinterpret_cast<T*>(&my_T);
    }
    

    这是定义的行为,还是只能复制到T类型的现有对象中?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Barry    6 年前