I've been putting a game engine together as a project to learn more about c++ for about 8 months now. I've got to a stage where in order to avoid allocating in constructors (in advice from university lecturers), I have virtual setup() methods for all of my objects, and a bool to flag whether the setup method has already been called. However I'm having all sorts of logical errors, and it's a huge pain not being able to do anything in the constructor because of allocation being done in setup. I've also been reading about RAII, and it seems that it might be better to just allocate in the constructor so that I don't have to call a setup method.
How bad is allocating memory via new in a constructor? And should I do so in order to conform to RAII?
Edit- just to clarify, people are pointing out using std::vector containers and the like. I'm talking about allocating memory for more objects, rather than for arrays and things. For example - a Button Object needs to create itself a TransformComponent , an AnimationComponent, and a RenderComponent. Currently, in setup() I would create them using new. Would using smart pointers etc mean I didn't need the new keyword?
The objects I'm creating are being forwarded to a Base Class method called addComponent(Component * ) that would store this component in a std::vector of Component * s, so I can't have these objects being cleaned up at then end of the method/constructor.
I was under the impression that
ButtonClass()
{
SomeComponent * sc = new SomeComponent ();
addComponent(sc);
}
Works just fine, but
ButtonClass()
{
SomeComponent sc = SomeComponent ();
addComponent(&sc);
}
would cause sc to be cleaned up, and the reference to it passed to addComponent would be a pointer to null memory.
If using a smart pointer negates this then I've misunderstood them, I thought they simply deleted things for me in a neater way than calling new and then delete.
The reasons I've been given to "Never allocate in a constructor" is that if the constructor fails, you can't recover that memory. But in agreement to a comment below, I've always suspected that if this were to happen I'd just terminate anyway....