make_pair 函数是在栈上还是堆上?

6

如果我从不同的作用域将其插入到映射中,是否需要分配一对?

#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;
    }
}

2
为什么你要用new创建unordered_map?为什么不直接使用unordered_map<string, string> inputs;呢? - Mankarse
1
你想要重新考虑动态创建指针输入,使用对象通常更合适。 - Martin York
3个回答

8
make_pair(key, value) 返回一个临时对象。该对象的生命周期在创建它的 完整表达式 结束时结束(基本上是在分号处)。
函数insert从该对创建一个新对象,并将其放入映射中。映射将存储此拷贝,直到映射被销毁或元素从映射中移除。

5
不,你没问题;整个映射条目的值,包括键值和映射值,在插入时会被复制到映射数据结构中(有时是移动)。
在C++11中,您可以通过m.emplace(key_value, mapped_value)稍微更直接地插入元素,这甚至不会创建临时的pair,或者更好的是,m.emplace(key_value, arg1, arg2, ...),它插入一个具有键key_value和映射值mapped_type(arg1, arg2, ...)的元素,甚至不为映射值创建临时对象。

5

没问题:

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

std::make_pair 返回值。

以上代码的效果与以下代码相同:

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

无论哪种情况,传递给insert()的值都会被复制(或移动)到地图中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接