简体   繁体   中英

Will structure like std::list<std::pair<string, string>> be copied when returned?

I have a function that is expected to extract a list of key values from a given string, where each key/value pair is represented by a std::pair , the function has the signature like below:

std::list<std::pair<string, string>> extract(const string &s)

If my implementation looks like:

list<pair<...>> kv_pairs;
for (....) {
  kv_pairs.push_back(make_pair(k, v));
}
return kv_pairs;

1) I don't want any copy to happen and I wonder if RVO/NRVO will be applied for the pairs inside the list and the list holding them.

2) If copy will happen in this case, what could be an alternative data structure implementing this without copying? I can think of a solution using unique_ptr<unorder_map<>> , but in my case, I only need to support iteration of the pairs in the list and don't need to support looking up value by their keys so I would like to avoid unnecessary hash calculation during insertion.

3) I know RVO/NRVO is compiler dependent behavior, is there any approach I can verify if these behavior happens or not easily?

If you are compiling targeting at least C++11, there are really only two possible outcomes:

  • Without RVO, the returned temporary will be used to move-construct the object to which the return value is assigned. This is basically just shuffling a few pointers around, and will take exactly the same amount of time (which is negligible) no matter how many items are in the list.
  • With RVO, the move-construction is elided.

Both outcomes are very fast and will not involve copying of the list structure.

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