Date: Sun, 27 Jul 2025 01:49:19 +0100
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?
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;
}
>
> 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?
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;
}
Received on 2025-07-27 00:49:35