C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Standardising 0xdeadbeef for pointers

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sat, 26 Jul 2025 20:55:19 -0400
On Sat, Jul 26, 2025 at 8:49 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> On Sat, Jul 26, 2025 at 10:54 PM Jonathan Wakely wrote:
> >
> > Any value written to a non-static data member by the destructor is a
> > dead store, it cannot be read after the destructor finishes. It is irrelevant
> > whether the object was initialized using placement new.
> >
> > As it's a dead store, the compiler can remove that store completely.
>
>
> Are you saying that the following program has undefined behaviour or
> that it's not guaranteed to print "deadbeef"?
>
> https://godbolt.org/z/6bcnz95Ed
>
> Specifically, are you saying that after the MyClass destructor has
> returned, that the first 8 bytes of 'buf' cannot be perused?

Since that `char[]` has not had its lifetime ended, you can look at
those bytes. But there is nothing in the standard that defines what
shall be in them. Once the object's lifetime ended, the contents of
its storage became unspecified.

As such, your code has, at best, unspecified behavior.

Also, I'm fairly sure that `ptr` does not point to the object created
by placement new in this case. If you don't want to actually store the
result of placement new in `ptr` (for some reason), you likely have to
launder the pointer before you can use it.

> And here it is copy-pasted:
>
> char unsigned buf[64u];
>
> struct MyClass {
> int *p = new int;
> ~MyClass(void)
> {
> delete p;
> p = (int*)(void*)0xdeadbeef;
> }
> };
>
> #include <iostream>
> #include <iomanip>
> using std::cout, std::hex, std::endl;
>
> int main(void)
> {
> MyClass *const ptr = static_cast<MyClass*>(static_cast<void*>(&buf));
> ::new(ptr) MyClass;
> ptr->~MyClass();
> // The loop on the next line is for Little Endian CPU's
> for ( unsigned i = 3u; i <= 3u; --i ) cout << hex << (unsigned)buf[i];
> cout << endl;
> }
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-07-27 00:55:35