Is gcc allowed to eliminate writes in a destructor?

Fabian Cenedese
Wed May 20 06:46:00 GMT 2015

At 20:55 19.05.2015, Mikhail Maltsev wrote:
>On 05/19/2015 08:31 PM, Norbert Lange wrote:
>> Hello,
>> I know that using a class after a destructor is called is a nasty
>> thing and I already changed the code, but I am curious if gcc is
>> allowed by the standard to eliminate stores to member variables.
>> I had code similar to the following:
>> Destructor:
>> if (_pAlloc) free(_pAlloc);
>> _pAlloc = 0;
>> _SomeData = 0;
>> what happened was that I explicitly called the destructor for
>> "cleanup" in another method. The free was called, and after the
>> instance went out of scope it was called again with the same address.
>Yes, that is allowed, because your program invokes undefined behavior.
>According to ISO C++11 standard:
>12.4. <...> "Once a destructor is invoked for an object, the object no
>longer exists; the behavior is undefined if the destructor is invoked
>for an object whose lifetime has ended (3.8). [ Example: if the
>destructor for an automatic object is explicitly invoked, and the block
>is subsequently left in a manner that would ordinarily invoke implicit
>destruction of the object, the behavior is undefined. — end example ]"

I think he's asking not about the double delete but the fact that the
member was seemingly not zeroed when the second call was made.

Two possibilities come to mind:
1. The debugger showed outdated values.
2. The object goes out of scope after the destructor so it doesn't matter
if _SomeData was set to 0 or not, no one can access it (legally) anyway.
Therefore it seems that gcc can omit this write unless it's volatile or so.
Similar to the warning "variable is set but not used" -> no need to do it.

bye  Fabi

More information about the Gcc-help mailing list