Don't use memory allocation functions unless you really need to. If your class needs a vector, always, just ad the std::vector member directly. No need to do memory allocation here.
In the cases where you need the dynamic vector, allocating and deleting it like in your first example is 100% correct.
In the second example, the call to std::swap is strictly spoken not needed, because the clear method will clear the vector, making it empty. One possible problem is that there is no guarantee that the vector will actually free the memory, giving it back to the operating system (or to the run time). The vector might keep the allocated memory just in case you will fill the vector right after clearing it. The call to std::swap may be a trick to 'force' the vector to free its internal data, but there is no guarantee that this will actually happen.
assert(vec != NULL)
?new
will not returnNULL
. – Pueblovec.clear();
. – Warthmanvec = std::vector<int>();
will suffice. – Husserlnothrow
form ofnew
, i.e.std::vector<int> *vec = new (nothrow) std::vector<int>;
, or simply drop theassert()
. That would address the comments @James and @Martin made. – Quakyvec.swap(std::vector<int>())
? That wouldn't need aclear()
. – Warthmanassert(vec != NULL)
is a way to tell the reader "I know thatnew
never returns null pointer". The main purpose of assertions is to serve as formalized comments, not to verify something that might or might not happen. If the author used anif (vec != NULL)
then your remark would be justified. But in case of anassert
it is completely off. Thisassert
is absolutely correct and absolutely appropriate use of an assertion. This is exactly what assertions are for. – Waddingtonassert(vec.empty())
after callingvec.clear()
as well to tell the reader "I know that the previous line emptied the vector?" – Puebloassert(vec.empty())
immediately after callingvec.clear()
is excessive in my opinion. But knowing about the popular misconceptions aboutnew
(and broken implementations), this assertion appears to be more than appropriate to me. – Waddington