boost::shared_ptr or CComPtr?
Hi, I haven't used either of these before, however my new project is probably going to have a lot of pointers that will need to be managed so I figured I had better start, I just wondered if one of them was preferred over the other, or what the difference is between them.
Also, if I implement them into my program, and have a vector of pointers, i.e
std::vector<Class*> vect, is it safe to just use vect.clear()?
Thanks again
Adam
Of those two, I've only used boost::shared_ptr and I am happy with it.
Notice that you'll have to either use `std::vector<boost::shared_ptr<Class> >' or `boost::ptr_vector<Class>' if you want any automatic deletion.
Notice that you'll have to either use `std::vector<boost::shared_ptr<Class> >' or `boost::ptr_vector<Class>' if you want any automatic deletion.
Quote:Original post by KnightAdzSafe how? you wouldn't get any compile time or runtime 'errors', but you would probably leak memory. std::vector<>::clear will destroy all objects in the vector. If the object has a destructor that destructor will be called. pointers do not have a destructor. If the pointer is pointing to an allocated block of memory that memory will remain allocated after the pointer is destroyed. This will result in a memory leak unless you somehow have a way to reference that allocated memory. Perhaps in another pointer, perhaps with a smart pointer.
Also, if I implement them into my program, and have a vector of pointers, i.e
std::vector<Class*> vect, is it safe to just use vect.clear()?
Hope this helps.
Yea, I was asking if, with a vector of smart pointers, would there be a memory leak if you just call vector.clear() on it? Anybody know?
Quote:Original post by KnightAdz
Yea, I was asking if, with a vector of smart pointers, would there be a memory leak if you just call vector.clear() on it? Anybody know?
No, there wouldn't be a memory leak. Containers of smart pointers work as expected.
I believe CComPtr is for automatic COM object reference counting - i.e. it has to hold a pointer to a COM object.
std::auto_ptr for stuff allocated and discarded within a function and boost::shared_ptr for things that persist.
std::auto_ptr for stuff allocated and discarded within a function and boost::shared_ptr for things that persist.
I use CComPtr for all D3D resources that are Com Objects and shared_ptr/weak_ptr for everything else.It really makes everything a lot easier.You don't have to deal with calling AddRef Release on D3D resources when you use CComPtr.And shared_ptr saves you from unfreed resources and dangling pointers.Just watch out for cyclic references and use weak pointers if necessary or redesign.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement