Into a class constructor, I need to create some objects on the fly and add them to a vector. Here is my code:
ContainerClass::ContainerClass() {
for (int i = 0; i < limit; i++)
elements.push_back(SubElement());
}
Is this the same thing with new SubElement()? Do I still need to free those SubElement() objects into the ContainerClass destructor?
Method 1:
If you have
std::vector<SubElement> elements;Then you would use
elements.push_back(SubElement()).SubElement()creates aSubElementon the stack and then a copy gets added to thevector.You should NOT call
deleteon the individual elements of thevector. They will be destructed and deallocated when thevectorgoes out of scope.Method 2:
If you have
std::vector<SubElement*> elements;Then you would use
elements.push_back(new SubElement()).new SubElement()creates aSubElementon the heap, and then the address of that element gets stored in thevector.You would need to call
deleteon the individual elements before thevectorgoes out of scope, otherwise you’ll create a memory leak. They will be destructed and deallocated only when you calldeleteon each of the elements.