简体   繁体   中英

Memory Handling C++ using Normal Pointer

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?

  1. pass by value the objA and make a copy in objB?

  2. 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? (like C# indeterministic garbage collector is not really ideal for performance critical application).

至少随便,听起来你正在寻找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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM