https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95349

--- Comment #41 from Andrew Downing <andrew2085 at gmail dot com> ---
> Thus for types without a non-trivial ctor/dtor you do not need to use
> placement new.  So take your example and remove the placement new.
> Does that change its semantics?

These are C++17 rules.

4.5/1) An object is created by a definition, by a new-expression, when
implicitly changing the active member of a union, or when a temporary object is
created.

6.8/1) The lifetime of an object of type T begins when: storage with the proper
alignment and size for type T is obtained, and if the object has non-vacuous
initialization, its initialization is complete.

double d;

My interpretation of the above rules would be that only a double object is
created in the storage for d because T in 6.8/1 is set to double by the
definition of d. According to these rules the only way to change the dynamic
type of the object in d's storage would be with placement new (pre C++20).
memcpy only overwrites the object representation. It doesn't affect it's type
or lifetime.

If you remove the placement new from my example, the program has undefined
behavior because it later accesses the double object with a uint64_t pointer.
With placement new in place, it accesses a uint64_t object in d's storage with
a uint64_t pointer.

In C++20 the placement new wouldn't be required because in addition to the
things above that create objects, you also have operations that implicitly
create objects of which memcpy is one. The rules are different than C's though.
The only objects that are or are not created are ones that would give the
program defined behavior. So in f1 where the uint64_t* pointing to d is
accessed, the compiler would have to make the second memcpy create a uint64_t
object in d's storage before copying the bytes to give the subsequent access
through a uint64_t* defined behavior. If you used placement new anyway, then
the second memcpy wouldn't have to create an object because the program would
already have defined behavior.

Reply via email to