I have a situation like below in which I have some problem in freeing the memory. Basically I have a vector that holds pointer to objects from classA. I have another classB that store the pointer of classA from the vector. It would make use of the objB. The problem is I need to operate on the vector to erase the pointer.
So how could I free the memory of objA as in the description below?
pass by value the objA and make a copy in objB?
delete the pointer to objA in the destructor of objB? ( I would not want to do that as well because it is only when the logic is fulfilled, I need to erase the pointer and delete the object. Otherwise, I would like to keep the object.
vectorA< classA*> vt; .... storing multiple pointer to objects to vector
classB* objB = new classB(vt.at(pos));
some logic performed. If it is fulfilled, need to erase a particular object from vector.
vt.erase(pos); ==> how do I free the memory if I deleted the pointer here? I could not call delete here because objB might need to use the objA later.
classB::classB(classA* objA){ this->objA = objA; }
So there any way to free the memory using Normal pointer as of the case above? As some of the replies directed me to using smart pointer, my question is are there any penalty imposed on the performance by using smart pointer? (l开发者_运维技巧ike C# indeterministic garbage collector is not really ideal for performance critical application).
At least offhand, it sounds like you're looking for shared_ptr
.
There should be a single owner of the A
objects, either vt
or objB
.
My inclination is towards the former.
Classes like objB
who want to use the A *
can use as vt.at( pos )
as you mentioned, but they should not keep a copy of the A *
.
If you have Visual Studio 2008 SP1 or later then you can use std::tr1::shared_ptr
. If you don't, you can use boost::shared_ptr
(the same class).
Store the shared_ptr in your vector, then you don't need to worry about deallocation of memory.
As others have pointed out, perhaps before you changed your question, a shared_ptr sounds like a good idea for the vector. You might want also to use a weak_ptr in the classB reference so that the vector is in control of the lifetime (classB would have to be able to handle when the weak_ptr goes stale).
For deallocation, by default shared_ptr deletes when the reference count goes to 0. You can specify a custom deleter for your shared_ptr that gives more control over what actually happens. Check out the delayed deallocation technique for Boost shared_ptrs.
精彩评论