unique_ptr的unordered_map:无法从迭代器获取值

时间:2013-07-06 14:46:02

标签: c++ gcc c++11

我正在尝试将unique_ptr存储在unordered_map中。我使用以下代码:

#include <unordered_map>
#include <memory>

int *function()
{
    std::unordered_map< int, std::unique_ptr<int> > hash;

    auto iterator=hash.find(5);
    return iterator->second().get();
}

当我尝试编译它(gcc 4.7.2)时,我收到以下错误:

test.cpp: In function ‘int* function()’:
test.cpp:9:29: error: no match for call to ‘(std::unique_ptr<int>) ()’

我不明白这段代码有什么问题。好像我需要使用另一种方法从迭代器中提取引用,但我知道没办法这样做。

Shachar

2 个答案:

答案 0 :(得分:2)

这一行:

return iterator->second().get();

应该是这样的:

return iterator->second.get();

second不是函数,而是地图中包含的std::pair的成员变量。您现在的代码尝试在成员变量上调用()运算符。但由于您的std::unique_ptr(存储在second中)没有定义这样的运算符,编译器无法找到它。

答案 1 :(得分:1)

secondstd::pair的成员变量,但您尝试将其称为函数。请改用以下内容。

return iterator->second.get();