2

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?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
DarthRubik
  • 3,927
  • 1
  • 18
  • 54
  • 2
    Related [“constructing” a trivially-copyable object with memcpy](https://stackoverflow.com/q/30114397/1708801) Also related [proposal p0593 Implicit creation of objects for low-level object manipulation](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0593r2.html) – Shafik Yaghmour Jul 28 '18 at 15:47
  • Why do you tag C++14? – xskxzr Jul 29 '18 at 11:08
  • 1
    @xskxzr Because if different versions of the language had different answer, I was most concerned with the c++14 version – DarthRubik Jul 30 '18 at 22:14

1 Answers1

5

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.

Barry
  • 286,269
  • 29
  • 621
  • 977