brad95411 brad95411 - 3 months ago 12
C Question

Using new with C++ Constructors that use C malloc

Can you safely use malloc in the constructor of a C++ class and use new to create instances of that object? I'm aware that it's unsafe to use the two in tandem with each other under normal circumstances, but in this instance is it possible/safe?

Answer
  1. Yes you can, but you should have a strong reason. The new operator invokes the constructor which in many ways is just like a regular class method. You should also add the free() part to the destructor.

    But please note, that if you malloc() a object the constructor of that object will not be called. I think there are very few reasons to call malloc() in a program: you probably wish to realloc() later, which is one reason. But you can always use native objects like containers.

  2. It's not unsafe to use the two ways of allocating memory in a program, you just have to be careful not to malloc() something and then delete it or new something and then free() it. But with malloc() you ALWAYS have to be careful about many things like it returning NULL and free()ing the allocated memory so it's not an extra thing.

    Once again, the most dangerous thing you can do is malloc() a object. Because as I already said, the constructor won't be called.