我可以隐式创建一个简单的可复制类型吗
Can I implicitly create a trivially copiable type
我的问题是:
假设类型 T
是简单可复制的....可以 "create" 这种类型的实例而不调用构造函数....像这样:
#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 类型对象中?
来自 [intro.object] 的规则是:
An object is created by a definition ([basic.def]), by a new-expression, when implicitly changing the active member of a union ([class.union]), or when a temporary object is created ([conv.rval], [class.temporary]).
None 这些事情发生在这里,所以你没有对象。存在隐式对象创建。该演员表在技术上是 UB,因为 my_T
处没有 T
类型的对象。
简单可复制的意思是,如果您随后将字节从 my_T
复制到另一个 T
对象,那么您将获得与刚刚复制 [=10] 相同的行为=] 使用复制构造函数。但是您仍然需要对象已经存在。
请注意,这是一个正在积极开展工作的领域,通过 P0593。有很多很多地方你真的只需要说 "I have a T
here" 就可以了,每个编译器都已经允许了。只是这个概念存在于我们今天在 C++ 中拥有的对象模型之外。
我的问题是:
假设类型 T
是简单可复制的....可以 "create" 这种类型的实例而不调用构造函数....像这样:
#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 类型对象中?
来自 [intro.object] 的规则是:
An object is created by a definition ([basic.def]), by a new-expression, when implicitly changing the active member of a union ([class.union]), or when a temporary object is created ([conv.rval], [class.temporary]).
None 这些事情发生在这里,所以你没有对象。存在隐式对象创建。该演员表在技术上是 UB,因为 my_T
处没有 T
类型的对象。
简单可复制的意思是,如果您随后将字节从 my_T
复制到另一个 T
对象,那么您将获得与刚刚复制 [=10] 相同的行为=] 使用复制构造函数。但是您仍然需要对象已经存在。
请注意,这是一个正在积极开展工作的领域,通过 P0593。有很多很多地方你真的只需要说 "I have a T
here" 就可以了,每个编译器都已经允许了。只是这个概念存在于我们今天在 C++ 中拥有的对象模型之外。