Do I need to allocate a pair if I insert it into a map from a different scope?
#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;
}
}
Stack accesses local variables only while Heap allows you to access variables globally. Stack variables can't be resized whereas Heap variables can be resized. Stack memory is allocated in a contiguous block whereas Heap memory is allocated in any random order.
The make_pair() function, which comes under the Standard Template Library of C++, is mainly used to construct a pair object with two elements. In other words, it is a function that creates a value pair without writing the types explicitly.
All variables allocated by malloc (or new in C++) is stored in heap memory. When malloc is called, the pointer that returns from malloc will always be a pointer to “heap memory”. All variables used as local variables – for example, when you just do int i = 0; – is stored on a function's stack.
The program code is in the program's code region. It's in neither the heap nor the stack. It's in a region of memory set up by the loader when the program is executed.
make_pair(key, value)
returns a temporary object. The lifetime of that object ends at the end of the full-expression in which it is created (at the semicolon, basically).
The function insert
creates a new object from that pair, which it puts into the map. The map stores this copy until the map is destroyed or the element is removed from the map.
Its 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 affect as:
inputs->insert( std::pair<std::string, std::string>(key, value) );
In both cases the value passed to insert() is copied(or moved) into the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With