Question

class AClass
{
    // ...
}

~

class AnotherClass
{
    public:
        // ...
        void AMethod()
        {
            // ...
            AClass * ac = new AClass(); // Dynamic memory allocation here
            m_Objects.push_back(ac);
            // ...
        }
        // ...
    private:
        // ...
        std::vector<AClass *> m_Objects;
        // ...
}

I want to add new objects of AClass to the vector m_Objects.
Is there any other way of doing this without doing dynamic memory allocation?

Was it helpful?

Solution

There are two things causing dynamic memory allocations here:

  1. vector::push_back
  2. new AClass()

Here is one idea how to reduce dynamic memory allocations.

First step is to call m_Objects.reserve(N); in the AnotherClass constructor, where N is the maximum number of AClass objects you want to keep at any given time. This reserves enough memory to remove the need for dynamic allocations by vector::push_back.

Second step is to make m_Objects contain objects instead of pointers, i.e. make it type std::vector<AClass> instead of std::vector<AClass*>. This allows you to skip new and directly create the new object by growing the container:

m_Objects.resize(m_Objects.size() + 1);

Now, there will be no dynamic allocation when adding a new object.

OTHER TIPS

If you mean "can I create new objects at runtime without doing dynamic allocation?" then the answer is no. That's what dynamic allocation is.

If you want to create some before they're immediately needed by creating them in bulk ahead of time, then that's plausible. Simply allocate a large number and then pull them out of an array or vector as needed.

Not so long as m_Objects is a vector of pointers, unless you were to store a pointer to an automatic (stack) variable. But that, undoubtedly, would be a very bad idea.

There are only two ways to allocate objects at runtime: dynamically on the heap, and on the call stack.

It is possible to instantiate multiple objects that are local (auto) variables within a function block by calling the function recursively, and adding these stack objects to your vector. But I'm pretty sure that's not what you really want.

That means that the only other way is to use new to dynamically create the new objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top