gpt4 book ai didi

c++ - 通过静态局部变量的引用/指针返回

转载 作者:行者123 更新时间:2023-11-30 00:45:52 26 4
gpt4 key购买 nike

我很困惑为什么如果我通过引用获取静态 unordered_map 而不是通过指针获取静态 unordered_map 会被清除...(您可以在此处执行代码:http://cpp.sh/4ondg)

是因为当引用超出范围时,它的析构函数被调用了吗?如果是这样,那么第二个 get 函数会得到什么?

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 &map;
}

};


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

最佳答案

当你做的时候

auto theMap = MyTestClass::getMap();

theMap 的类型推导为 std::unordered_map<int, int> – 不是引用。因此,函数调用返回的引用被复制到局部变量theMap中。 ;当你修改 theMap ,您只是在修改此拷贝。

要存储引用,将其声明为 auto& :

auto& theMap = MyTestClass::getMap();

然后您将按预期修改原始对象。

关于c++ - 通过静态局部变量的引用/指针返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41154358/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com