简体   繁体   中英

Should rvalue reference qualifier return rvalue reference?

I am investigating whether returning rvalue reference from rvalue ref-qualifier function is really good idea. Lets say we have:

class DataPack {
 public:
  std::vector<int> data;

  DataPack(std::initializer_list<int> d) : data{d} {}

  std::vector<int>& get_data() & {
    return data;
  }
  std::vector<int>&& get_data() && {
    return std::move(data);
  }
  // This version fixes for-loop problem (see below)
  //std::vector<int> get_data() && {
  //  return data;
  //}
};

then if I want to get data without making temporary I can use following:

auto my_data = DataPack{1,2,3}.get_data();

but suppose I want to use following code:

for (auto v : DataPack{1,2,3}.get_data()) {
  std::cout << v << ", ";
}

now this is UB, as get_data() returns reference to temporary which is destroyed after full statement.

Maybe this can be somehow fixed for such for - loops? Or maybe we should return by value and hope that RVO will work as expected? Becasue as it is above seems to me as not very safe.

std::vector<int>&& get_data() && {
   return std::move(data);
}

This should return a std::vector<int> instead, then there's no problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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