Can I implicitly create a trivially copiable type

Deadly 提交于 2020-01-04 14:13:41

问题


My question is this:

Suppose type T is trivially copyable....can "create" an instance of this type without calling a constructor....like so:

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

Is this defined behavior, or can I only copy into an existing object of type T?


回答1:


The rule, from [intro.object], is:

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 of those things is happening here, so you don't have an object. There is implicit object creation. That cast is technically UB because there is no object of type T at my_T.

What trivially copyable means is that if you then copied the bytes from my_T into another T object, then you would get the same behavior as if you'd just copied the T using the copy constructor. But you still need the objects to have already existed.


Note that this is an area that is being actively worked on, via P0593. There are many, many places where you really just need to say "I have a T here" and have that work, and every compiler already allows for that. It's just that that concept exists far outside of the object model that we have in C++ today.



来源:https://stackoverflow.com/questions/51572788/can-i-implicitly-create-a-trivially-copiable-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!