Make_pair on the stack or heap?

Do I need to highlight a pair if I insert it into a card from another area?

#include <iostream> #include <string> #include <unordered_map> #include <utility> using namespace std; void parseInput(int argc, char *argv[], unordered_map<string, string>* inputs); int main(int argc, char *argv[]) { unordered_map<string, string>* inputs = new unordered_map<string, string>; parseInput(argc, argv, inputs); for(auto& it : *inputs){ cout << "Key: " << it.first << " Value: " << it.second << endl; } return 0; } void parseInput(int argc, char *argv[], unordered_map<string, string>* inputs) { int i; for(i=1; i<argc; i++){ char *arg = argv[i]; string param = string(arg); long pos = param.find_first_of("="); if(pos != string::npos){ string key = param.substr(0, pos); string value = param.substr(pos+1, param.length()-pos); inputs->insert( make_pair(key, value) );//what happens when this goes out of scope } } for(auto& it : *inputs){ cout << "Key: " << it.first << " Value: " << it.second << endl; } } 
+4
source share
3 answers

His fine:

 inputs->insert( make_pair(key, value) );//what happens when this goes out of scope 

std :: make_pair returns the result by value.

The above has the same effect as:

 inputs->insert( std::pair<std::string, std::string>(key, value) ); 

In both cases, the value passed to insert () is copied (or moved) to the card.

+4
source

make_pair(key, value) returns a temporary object. The lifetime of this object ends at the end of the full expression in which it was created (at the semicolon, basically).

The insert function creates a new object from this pair, which is placed on the map. The card saves this copy until the card is destroyed or the item is removed from the card.

+5
source

No, you're fine; the entire value of the map value, consisting of the key value and the displayed value, is copied to the map data structure (or sometimes moved) when it is inserted.

In C ++ 11, you have a slightly more direct way to insert an element through m.emplace(key_value, mapped_value); that doesn’t even create a temporary pair or even better, m.emplace(key_value, arg1, arg2, ...) , which inserts an element with the key key_value and the displayed value mapped_type(arg1, arg2, ...) , without even creating a temporary value for the displayed value.

+4
source

Source: https://habr.com/ru/post/1392618/


All Articles