std::vector
manages its own memory. That means that, when the destructor of a vector is invoked the memory held by the vector is released. std::vector
also invokes an object's destructor when it is removed (through erase
, pop_back
, clear
or the vector's destructor).
When you do this:
Radio newradio(radioNum);
m_radios.push_back(newradio);
You add a copy of newradio
(created using Radio
's copy constructor) to the vector. newradio
will be destroyed when it goes out of scope, and the copy will be destroyed when it is removed from the vector (as for any object).
That's an important point: std::vector
only stores copies of an object, which means the object must have a meaningful copy constructor (and an assignment operator, but that's another issue). If you have a vector of pointers, then the pointer itself will be copied, and not what it points to. Note that this behavior is the same for every standard container (like std::list
or std::set
).
As a rule of thumb, if you're not using pointers, then you don't have to worry about releasing the memory yourself.
In C++11, most standard containers (including vector
) have an emplace_back
method that constructs an object in place at the end of the container. It takes a bunch of parameters and calls the constructor that best matches those parameters (or fails if no such constructor exist), using said constructor to create the object, without any copy, at the end of the container. So, the above code could be rewritten as:
m_radios.emplace_back(radioNum); // construct a Radio in place,
// passing radioNum as the constructor argument
Also in C++11, containers are usually move aware, so they no longer require objects to be copiable: if they are movable, then the container will move its contents as required (such as during reallocations, for instance). Copiable types are still required if you want to copy the vector.