I've created a std vector and pushed back a bunch of objects onto it using the std move, such as:
vector<unique_ptr<Foo> > myVec;
unique_ptr<Foo> a = make_unique<Foo>();
unique_ptr<Foo> b = make_unique<Foo>();
myVec.push_back(move(a));
myVec.push_back(move(b));
So far, so good.
Later on, I pass a reference of myVec to a function and try to access the data in the vector using the []-operators.
void someFunc(vector<unique_ptr<Foo> > &myVec)
{
Foo* anObj = myVec[0];
}
After some reading, my guess is that this approach is not going to work, because the std vector will try and make a copy and unless I provide a copyconstructor on Foo that avoids actually making a copy it wont ever work. Am I correct? I think I saw some posts about using iterators, but I'd rather not if I dont have to.
EDIT1:
I did manage to work around it by the following (using iterator and then get to get the raw pointer)
void someFunc(vector<unique_ptr<Foo> > &myVec)
{
int offset = 0; // Or some other offset into the vector
auto it = myVec.begin() + offset;
Foo* anObj = it.get();
// ... Do something using anObj here...
}
I would think this is the way to go, as long as you dont foolishly try to retain the anObj and then free it manually somewhere. I could of course transfer ownership temporarly until Im done with it and then return the ownership but it feels like such a hassle. Any thoughts on the above approach?
Thanks in advance, /Jimmie
std::unique_ptr
, you'll see if has a couple ways to return the pointer: namelyrelease()
andget()
- read about them and decide which you want to do, or use the pointer directly frommyVec[0]
instead of copying it anywhere. – Tony DelroymyVec[0]
makes a copy. It does not. – Lightness Races in Orbit