[HH] c++ strings?
Matthew Gillen
me at mattgillen.net
Tue Nov 20 12:04:12 EST 2012
On 11/20/2012 10:34 AM, Mark Woodward wrote:
> On 11/20/2012 10:06 AM, Matthew Gillen wrote:
>> Likewise with malloc vs. new: they are NOT freely interchangeable.
>> Managing a C++ class with 'new/delete' will ensure that
>> constructors/destructors get called. Managing that same object with
>> malloc/free does not invoke constructor/destructor pairs, it merely
>> allocates memory. Furthermore, there is no guarantee that the way
>> 'new' and 'malloc' manage memory is compatible; e.g. you could have
>> issues if you 'new' and object and then 'free' it, or 'malloc' and
>> object then 'delete' it.
> New/delete are interesting. Typically, a pointer returned by "new" can
> be freed by "free," however, new and delete involve the constructors and
> destructors.
What you're suggesting is not portable, as in "the language spec does
not guarantee that you can 'free' something allocated via 'new'.
There's a school of thought that says "screw the spec, whatever gcc
allows/supports is what matters", but it's also almost always a bad idea
(do you want to verify that your class' destructor is empty, along with
any inherited destructors? If those destructors are non-empty, are you
going to duplicate the code contained therein for the sake of being able
to call 'free'?).
Every time I've relied on some nice feature of gcc that isn't explicitly
spelled out in the spec, I end up getting burned when someone down the
line eventually makes me compile it on a microsoft compiler...
More information about the Hardwarehacking
mailing list