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?
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 c++ object the constructor of that object will not be called. I think there are very few reasons to call
malloc() in a c++ program: you probably wish to
realloc() later, which is one reason. But you can always use native c++ objects like stl containers.
It's not unsafe to use the two ways of allocating memory in a c++ 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
free()ing the allocated memory so it's not an extra thing.
Once again, the most dangerous thing you can do is
malloc() a c++ object. Because as I already said, the constructor won't be called.