简体   繁体   English

C++ STL 容器 - 随移动弹出

[英]C++ STL container - pop with move

Is there a STL container (no Boost) from which an element can removed and moved to an lvalue?是否有一个 STL 容器(无 Boost),可以从中删除元素并将其移动到左值?

Say I have a std::vector of large objects and a variable to which I want to pop an element from the vector.假设我有一个大对象的std::vector和一个我想从向量中弹出一个元素的变量。

var = vec.back();  // non-move assign op
vec.pop_back();    // dtor

var = containerWithMovePop.pop_and_return();  // move assign-op

It's not like performance is so important, I just want to know if it's possible.性能并不是那么重要,我只是想知道它是否可能。

As @aeschpler says, this works正如@aeschpler 所说,这有效

auto var = std::move(vec.back()); 
vec.pop_back();

vec.back() will be empty (if string) or same (if int), or whatever (depends on the type) between back and pop_back, but that's fine. vec.back() 将是空的(如果是字符串)或相同的(如果是整数),或者 back 和 pop_back 之间的任何内容(取决于类型),但这没关系。 As the destructor runs in pop_back() there will be very little to do there.由于析构函数在 pop_back() 中运行,因此几乎没有什么可做的。

We might get pop_back() to return T in the future now that we have move semantics (as ppl noted, we didn't when std::vector<> was specced), but likely it'd be a new method so to not destroy backward compatibility.既然我们有移动语义,我们可能会在未来让 pop_back() 返回 T(正如 ppl 所指出的,我们在指定 std::vector<> 时没有这样做),但它可能是一个新方法,所以不破坏向后兼容性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM