0

I am trying to manage a vector of Objects for class A.

Class A has a static std::map which maps its internal entity to its 'this' pointer on it's constructor, which looks like

std::map< id,A *> idmap;

I am aware that vector does a deep_copy while doing a push_back(). So creating an object, and the pushing into the vector is calling the constructor twice, so it would be calling the mapping procedure twice. And I'm not happy with this.

A solution to this problem may be using a vector of pointer rather that vector of objects, but I'm little bit worried about the memory leak problem that I could somehow make a mistake on it because there are lots of spots that this object(of Class A) is being referred.

So, what might be the delicate way to manage in this case? Is using vector of pointers the only proper solution?

6
  • Please show complete code. Where's the vector?
    – Kerrek SB
    Dec 8, 2015 at 13:28
  • 2
    Have you looked at emplace_back? Instead of constructing an object then calling push_back you can tell the vector to construct it in place. You still need to be careful about the id entry in that map when vector needs to move all the objects to increase capacity. But that can be covered with correct move semantics in the object.
    – JSF
    Dec 8, 2015 at 13:33
  • 1
    Use std::vector<std::unique_ptr>. Solves your copy and memory leak concerns. Dec 8, 2015 at 13:41
  • 1
    If you need access to these pointers outside of your class by other resources you could use std::vector<std::shared_ptr<YourObject>> If this class will be the sole owner where no other class or object has access to it then you can use std::vector<std::unique_ptr<YourObject>> Dec 8, 2015 at 15:29
  • @JSF Normally move semantics would be FTW here but there's a peculiar thing going on in this case where the op is mapping the this pointer of each class instance somehow, and the primary temptation seems to be in avoiding erasing and inserting redundantly. So for this kind of case, probably the ideal solution is std::vector<std::unique_ptr<A>> -- unique_ptr instead of shared_ptr assuming we translate whatever he was doing originally as closely as possible.
    – user4842163
    Dec 9, 2015 at 1:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.