C++ Logo

std-discussion

Advanced search

Re: objects with no lifetime for validation

From: Jens Maurer <jens.maurer_at_[hidden]>
Date: Sat, 27 May 2023 14:20:10 +0200
On 27/05/2023 10.16, Federico Kircheis via Std-Discussion wrote:
> On 27/05/2023 07.36, Federico Kircheis via Std-Discussion wrote:
>> On 26/05/2023 23.23, Jens Maurer wrote:
>>>
>>> On 26/05/2023 21.30, Federico Kircheis via Std-Discussion wrote:
>>>> I know that it is not possible to create objects out of thins air:
>>>>
>>>> int i = 42;
>>>> char buffer[sizeof(int)];
>>>> std::memcpy(buffer, &i, sizeof(int));
>>>>
>>>> int* j = reinterpret_cast<int*>(buffer);
>>>> *j; // UB, even if *j == i, as j does not point to an int object
>>>
>>> This is not accurate since implicit object creation has been introduced.
>>> Please read [intro.object] in its entirety.
>>
>> Mhm, I'll check again...
>>
>
>
> I think you where implying here that memcpy implicitly creates an object
> of type int, and thus *j is valid.
> Is that correct?

No.

[intro.object] p13 says that starting the lifetime of an array of unsigned
char implicitly creates objects (oops, yours is an array of char, so that
doesn't work), and memcpy then just copies the object representation
into the already-existing object per [basic.types.general] p3.

> if i was const, would then memcpy create implicitly a const int object?

Since memcpy doesn't do anything special, "const int i" is fine, too.

Jens

Received on 2023-05-27 12:20:13