What is the proper way of pushing a new object element onto a std::vector? I want the data to be allocated in the vector. Will this copy the object newradio into the vector and then get rid of newradio when it goes out of scope (e.g. out of the stack)?
vector<Radio> m_radios;
Radio newradio(radioNum);
m_radios.push_back(newradio);
And then when I free the object containing m_radios, will this free all the memory allocated by the vector?
std::vectormanages its own memory. That means that, when the destructor of a vector is invoked the memory held by the vector is released.std::vectoralso invokes an object’s destructor when it is removed (througherase,pop_back,clearor the vector’s destructor).When you do this:
You add a copy of
newradio(created usingRadio‘s copy constructor) to the vector.newradiowill 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::vectoronly 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 (likestd::listorstd::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 anemplace_backmethod 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: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.