[Interest] Double destruction of Qt objects in Qt example code?

K. Frank kfrank29.c at gmail.com
Sun Aug 19 21:15:02 CEST 2012

Hi Oliver!

One minor point (below):

On Sun, Aug 19, 2012 at 11:18 AM, Till Oliver Knoll
<till.oliver.knoll at gmail.com> wrote:
> Am 19.08.12 01:29, schrieb K. Frank:
> ...
>> However, it is not legal to call delete on a local (non-new'ed) variable,
>> and the error occurs right when delete is called, rather than later when
>> the variable goes out of scope.
> Just to be precise: it /is/ legal C++ to call delete on a stack
> variable, at least in the syntactical sense:

Yes, it is syntactically legal.  But it is illegal -- perhaps we could say
semantically illegal.  The standard (I'm pretty sure) says that it's
undefined behavior.

>   SomeObject someObject; // allocated on the stack
>   delete &someObject; // does complain just fine
> My gcc on Mac did not even issue a big fat warning with the standard
> qmake settings,

Well, in your specific example, the compiler could deduce that you're
doing something illegal, and flag it.  But, in general, when you call
delete on some pointer:

   delete pObject;

the compiler can't know whether the the pointer is a pointer to a
new'ed variable (or even whether the pointer is any sort of valid pointer).
So the compiler didn't catch an error that, in general, it can't catch
(and isn't required by the standard to try to catch).

> but not surprisingly above code crashes immediatelly at
> that point, just as K. Frank said:
>   error for object 0x7fff5fbff7cf: pointer being freed was not allocated

That's probably the best outcome.  Because it's undefined behavior,
on other implementations it could lead to subtler and harder to debug

> ...
> Cheers,
>   Oliver


K. Frank

More information about the Interest mailing list