[英]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.有时我想将sp类型的对象从 v1 的末尾移动到 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?这部分代码是我程序中的一个重要瓶颈,由于我在移动后不需要 v1 中的值,我想如果我移动它们而不是复制我可以避免额外的计数器增量/减量,对吗? 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!).顺便说一句,使用不同的指针类型不是一种选择 - 类型 T 是非常明确地共享的(只是不是在这个特定实例中!)。
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();
You're not invoking the move constructor.您没有调用移动构造函数。 Nothing about the emplace_back
call makes it clear v1
is no longer needed.关于emplace_back
调用的任何内容都没有明确说明不再需要v1
。 You probably need a std::move
in there.你可能需要一个std::move
在那里。
You probably want:你可能想要:
v2.emplace_back(std::move(v1.back()));
v1.pop_back();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.