Sol*_*lti 1 c++ unordered-map pass-by-reference
我很困惑为什么静态unordered_map被清除如果我通过引用得到它但不是如果我通过指针得到它...(你可以在这里执行代码:http://cpp.sh/4ondg)
是因为当引用超出范围时,它的析构函数会被调用吗?如果是这样,那么第二个获取功能会得到什么?
class MyTestClass {
public:
static std::unordered_map<int, int>& getMap() {
static std::unordered_map<int, int> map;
return map;
}
static std::unordered_map<int, int>* getMapByPointer() {
static std::unordered_map<int, int> map;
return ↦
}
};
int main()
{
// By reference
{
auto theMap = MyTestClass::getMap();
std::cout << theMap.size() << std::endl;
theMap[5] = 3;
std::cout << theMap.size() << std::endl;
}
{
auto theMap = MyTestClass::getMap();
std::cout << theMap.size() << std::endl;
theMap[6] = 4;
std::cout << theMap.size() << std::endl;
}
// By pointer
{
auto theMap = MyTestClass::getMapByPointer();
std::cout << theMap->size() << std::endl;
(*theMap)[5] = 3;
std::cout << theMap->size() << std::endl;
}
{
auto theMap = MyTestClass::getMapByPointer();
std::cout << theMap->size() << std::endl;
(*theMap)[6] = 4;
std::cout << theMap->size() << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
当你这样做
auto theMap = MyTestClass::getMap();
Run Code Online (Sandbox Code Playgroud)
theMap推断的类型是std::unordered_map<int, int>- 不是参考.因此,函数调用返回的引用被复制到局部变量中theMap; 修改时theMap,您只修改此副本.
要存储引用,请将其声明为auto&:
auto& theMap = MyTestClass::getMap();
Run Code Online (Sandbox Code Playgroud)
然后,您将按预期修改原始对象.