On Mon, 08 Apr 2013 16:16:07 +0100, Minas Mina <[email protected]> wrote:

Sorry, if it wasn't clear. I was talking about C++.

Even if you are not mixing the two, you can still get f*** up.

struct S
{
        S()
        {
                cout << "S()\n";
        }
};

int main()
{
        S *s = new S(); // constructor is called
        
        S *s2 = (S*)malloc(sizeof(S)); // constructor is NOT called
}

So you see an innocent struct type and you decide to use malloc instead of new... If it has a constructor/destructor/... those will not be called. It's just asking for trouble.

This is exactly what I was talking about.. you're expecting memory allocation to perform object construction.. it doesn't, never has, never will. :p

There is a reason malloc returns void* you know, because it doesn't return an initialised S*, it doesn't return a initialised anything, not even an initialised char*, it just returns a block of memory which you are expected to initialise yourself.

Separate the 2 concepts of memory allocation and object construction/initialisation in your head and and you'll never make this mistake again :)

R

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

Reply via email to