vector::clear :Memory Issue
Vector::Clear() will erase the elements in the vector array.
The issue is that if we pass objects in vector list then Clear() will delete the memory of objects or not.
I post my sample:
CData *m_data = new CData();
vector<CData*> m_logd开发者_Python百科ata;
m_logdata.push_back(m_data);
m_logdata.clear();
will this code delete the memory allocated by m_data or simply remove the element in the vector list?
Regards, karthik
There's no Vector, there is a vector though.
vector.clear() will destruct the objects in the vector. If these objects are pointers, it will not delete the pointed to objects.
struct Foo {
};
vector<Foo> vec1;
vector<Foo *> vec2;
vec1.push_back(Foo());
vec2.push_back(new Foo());
vec1.clear(); // Will destruct the Foo instances
vec2.clear(); // Will not delete the pointed to Foo instances
On your edited post:
m_logdata.clear();
This will not delete your CData
instance. It'll simply destruct the pointer which is a no-op.
EDIT: In response to comment.
for (size_t p = 0; p < m_logdata.size(); ++p)
delete m_logdata[p];
m_logdata.clear();
The question is quite vague... but either way, I guess that you are wondering if pointers stored in a vector
would automatically be deleted when clear()
is called.
This is not the case. Whatever you store in a vector
will have its destructor called when clear()
occurs. And the destructor of a primitive type (such as a pointer) does.. nothing.
From my SGI implementation:
/**
* Erases all the elements. Note that this function only erases the
* elements, and that if the elements themselves are pointers, the
* pointed-to memory is not touched in any way. Managing the pointer is
* the user's responsibilty.
*/
void
clear() { erase(begin(), end()); }
To properly delete items pointers in any STL container, the easiest way is to create a functor and apply it on every item:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <functional>
#include <algorithm>
template <typename ValueT>
struct func_delete : public std::unary_function<ValueT,void>
{
void operator()( ValueT& item ) { delete item; }
};
struct Foo
{
~Foo() { std::cout << "Foo::~Foo()" << std::endl; }
};
template <typename ContainerT>
void delete_container( ContainerT& container )
{
std::for_each( container.begin(), container.end(), func_delete<typename ContainerT::value_type>() );
}
int main( int argc, char** argv )
{
std::vector<Foo*> foos;
foos.push_back( new Foo );
foos.push_back( new Foo );
foos.push_back( new Foo );
// Either of these two lines will work
//std::for_each( foos.begin(), foos.end(), func_delete<Foo*>() );
//delete_container( foos );
foos.clear();
return EXIT_SUCCESS;
}
精彩评论