C++ -- how to design the data structure so that it can avoid the memory leak [duplicate]
Possible Duplicate:
vector of pointer to object - how to avoid memory leak?
Hello all,
I have the following code,
vector<Student*> vec;
// populate vec with Student pointers
Then sort(vec.begin(), vec.end(), ...)
to sort the Student based on the score.
Here is the question,
Because vector stores the pointers, we have to later remember to remove it manually. However, we cannot store auto_ptr inside the vector.
Is there a better way for this? Store a smart pointer inside v开发者_Go百科ector? How to design this smart pointer?
Thank you
To expand on Colin's answer- auto_ptr is not useful with containers as it can not be copied. What you are looking for is a reference counted smart pointer- either a shared pointer or an intrusive pointer will do the job. Boost supplies several smart pointers for you- including shared_ptr, and intrusive_ptr. Most likely (infered from your original question) boost::shared_ptr is what you want.
Like this: boost smrtpntr, or you could template-specialize vector to delete the objects in it's destructor, which could have unintended consequences if not done carefully.
On the flip side of using a vector of smart pointers, as Colin and MarkD have suggested, you could also use boost::ptr_vector
精彩评论