Search code examples
c++memory-leaksdynamicobject

dynamic object creation in vector


so i would like to have vector<OtherClassName> theVector as a member of a BaseClass

i am wondering in many ways that i can get a memory leaks...

will doing this results in memory leaks?

BaseClass::someFunction(){
   OtherClassName * c = new OtherClassName();
   theVector.push_back((*c));
}

i'm a beginner in C++, learning from the internet.


Solution

  • will doing this result in memory leaks?

    Yes, this will result in a memory leak. Every object allocated with new must be destroyed with delete. Failing to do so causes a memory leak.

    In particular, what you are storing in your vector here is a copy of the object allocated with new. If you want your container to hold objects of a certain class, it is enough to do:

    BaseClass::someFunction()
    {
        OtherClassName c;
        theVector.push_back(c);
    }
    

    Notice that the vector, like all containers of the C++ Standard library, has value semantics: this means that what you are inserting in the vector is a copy of the object you pass to push_back(). Further modifications to the original objects won't be reflected by the state of the object contained in the vector, and vice versa.

    If you want this to happen, i.e. if you need reference semantics, you will have to let your vector contain (possibly smart) pointers. For instance:

    #include <memory>
    
    // theVector would be declared as:
    // std::vector<std::shared_ptr<OtherClassName>> theVector;
    
    BaseClass::someFunction()
    {
        std::shared_ptr<OtherClassName> pC = std::make_shared<OtherClassName>();
        theVector.push_back(pC);
    }
    

    Manual memory management through new and delete is considered bad programming practice in Modern C++, because it easily leads to memory leaks or undefined behavior, and negatively affects the design of your program in terms of robustness, readability, and ease of maintenance.