On Mon, 08 Apr 2013 15:24:06 +0100, Minas Mina <minas_mina1...@hotmail.co.uk> wrote:

On Monday, 8 April 2013 at 13:01:18 UTC, Regan Heath wrote:

I've always hated the fact that C++ has 2 memory models new/delete and malloc/free and I've never liked new/delete because it doesn't allow anything like realloc - why can't I reallocate an array of char or wchar_t??


Try using malloc on something that contains a type with a constructor inside and you'll see. The constructor will not be called :)

Are you talking about C++ or D here?

Memory allocation and object construction are separate concepts, malloc is for the former, not the latter. "new" on the other hand ties them both together .. except that "placement" new can be used to separate them again :)

As in..

#include <stdlib.h>
#include <new.h>

class AA
{
public:
  AA()  { printf("AA\n"); }
  ~AA() { printf("~AA\n"); }
};

class BB
{
  AA a;
public:
  BB()  { printf("BB\n"); }
  ~BB() { printf("~BB\n"); }
};

void main()
{
  void *mem = malloc(sizeof(BB));
  BB *b = new (mem) BB();
  delete b;
}

The above outputs:
AA
BB
~BB
~AA

as expected. malloc is used for memory allocation and placement new for construction.

malloc and friends are bad heritage due to C compatibility. I stay away from them.

Mixing the 2 in the same piece of code is just asking for bugs - like trying to free something allocated with "new[]" for example.. *shudder*. There is nothing "bad heritage" about malloc, or more especially realloc, you try doing the equivalent of realloc with new .. it's not possible.

R

--
Using Opera's revolutionary email client: http://www.opera.com/mail/

Reply via email to