Reputation: 1302
I'm using C++14. Let's assume I have a class X
and a std::vector<X> mVector
.
I also have the following code:
std::shared_ptr<X> AddX(const X &x)
{
mVector.push_back[x];
return std::shared_ptr<X>(&mVector[mVector.size()-1])
}
This method inserts the object x
into mVector
and returns me a shared pointer to this inserted object.
X x1;
shared_ptr<X> pX1 = AddX(x1);
Everything works fine, but when I insert a second object
X x2;
shared_ptr<X> pX2 = AddX(x2);
pX1
doesn't point to the inserted object x1
, because the last push_back has moved its position in memory (seen after hard debug). This is a pity for me, because my program needs these pointers to work correctly, and mVector
needs to be dynamic, it's being all the time modified (with new X
objects, or old ones are deleted).
How can I fix this? I guess than a way could be working with the objects indices instead of their pointers, but this would penalize my execution time because I should update many attributes every time I modify mVector
. Is there a posibility to manage it and still working with pointers?
Upvotes: 0
Views: 75
Reputation: 62603
First things first. Everything works fine
. No. Nothing works fine. You should not return a shared pointer (or any other smart pointer for this matter) to the memory which you didn't allocate yourself.
Vector manages its own members, and if you try to manage vector
elements, you are in for a big trouble.
Now to your question. Looks like vector
is not a good container for your goal. Provided you use normal pointer (rather than the smart one) you can use, for example, std::deque
- as long as you do not insert in the middle of the queue, and only use push_back
and push_front
.
Another option would be to use indices instead of the pointers and keep vector
around - indices will remain the same even after insertions.
Upvotes: 9