quant
quant

Reputation: 23092

How do I move a shared_ptr object between containers with move semantics?

I have two vectors which contain pointers to shared objects in my program:

typedef shared_ptr<T> sp;
std::vector<sp> v1;
std::vector<sp> v2;

And sometimes I want to move an object of type sp from the end of v1 to the end of v2. This section of code is a significant bottleneck in my program, and since I have no need for the value in v1 after the move I was thinking that if I move them rather than copying I can avoid the extra counter increment/decrement, right? So here's what I've done:

// move constructor for new element of v2:
v2.emplace_back(v1.back());

// the move constructor should have made the element in v1 null:
assert(v1.back() == nullptr); // FAIL - why?

// now remove the dead element at the end of v1
v1.pop_back();

What have I done wrong here? Is this not the right way? BTW using a different pointer type is not an option - type T is quite unambiguously shared (just not in this particular instance!).

EDIT: Here is my implementation of David's solution:

// move constructor for new element of v2:
v2.emplace_back(std::move(v1.back()));

// the move constructor should have made the element in v1 null:
assert(v1.back() == nullptr); // ok!

// now remove the dead element at the end of v1
v1.pop_back();

Upvotes: 3

Views: 2463

Answers (1)

David Schwartz
David Schwartz

Reputation: 182819

You're not invoking the move constructor. Nothing about the emplace_back call makes it clear v1 is no longer needed. You probably need a std::move in there.

You probably want:

v2.emplace_back(std::move(v1.back()));
v1.pop_back();

Upvotes: 7

Related Questions