Search code examples
c++dynamic-memory-allocation

How can I add more objects of a class to a vector without doing dynamic memory allocation?


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?


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.