简体   繁体   English

标准::向量<t> ::emplace_back 在右值引用上</t>

[英]std::vector<T>::emplace_back on an rvalue reference

I have the following function inside a class我在 class 中有以下 function

  void add_state(std::string &&st) {
    state.emplace_back(st);           // state is a vector
  }

st is an l-value (rvalue reference to a string in this case) based on my understanding.根据我的理解, st是一个左值(在这种情况下是对字符串的右值引用)。 If, I want to move st into the last element in state , should I be using state.emplace_back(std::move(st)) ?如果我想将st移动到state的最后一个元素中,我应该使用state.emplace_back(std::move(st))吗? What happens if I leave it the way it's written above?如果我按照上面写的方式保留它会发生什么?

EDIT 1 (example of how add_state is called):编辑 1(如何add_state的示例):

// do a series of operations to acquire std::string str
add_state(std::move(str)); 
// also note that str will never be used again after passing it into add_state

Would it be better if I made add_state(std::string &st) instead?如果我add_state(std::string &st)会更好吗? In this case, I think I can just simply call it with add_state(str) ?在这种情况下,我想我可以简单地用add_state(str)调用它?

[...] should I be using state.emplace_back(std::move(st)) ? [...] 我应该使用state.emplace_back(std::move(st))吗?

Yes.是的。

What happens if I leave it the way it's written above?如果我按照上面写的方式保留它会发生什么?

You have correctly identified that st is an lvalue, so it gets copied.您已正确确定st是一个左值,因此它被复制了。

Would it be better if I made add_state(std::string &st) instead?如果我add_state(std::string &st)会更好吗? In this case, I think I can just simply call it with add_state(str) ?在这种情况下,我想我可以简单地用add_state(str)调用它?

You could, but you shouldn't.你可以,但你不应该。 std::move is just type juggling, it does not do anything by itself (in particular, it doesn't move anything). std::move只是类型杂耍,它本身不会做任何事情(特别是,它不会移动任何东西)。 The actual operation happens inside std::string::basic_string(std::string &&) which is called by emplace_back after it receives the std::string && .实际操作发生在std::string::basic_string(std::string &&)内部, emplace_back在收到std::string &&后调用它。 Making your own parameter an lvalue reference has no effect other than surprising the caller, who gets their std::string eaten without an std::move on their part.使您自己的参数成为左值引用除了让调用者感到惊讶之外没有任何效果,调用者会在没有std::move的情况下吃掉他们的std::string

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

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