通过静态局部变量的参考/指针返回

return by reference/pointer of a static local variable

本文关键字:指针 返回 参考 静态 局部变量      更新时间:2023-10-16

我对为什么如果我通过参考获得静态unordered_map被清除,而不是通过指针获得它的原因...(您可以在此处执行代码:http:/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 &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();

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

当将静态图分配给本地变量时,您会无意中复制静态图。在:

auto theMap = MyTestClass::getMap();

auto被推论为std::unordered_map<int, int>,而不是std::unordered_map<int, int>&,它导致新对象从返回的参考文献中复制进行委员会化。因此,theMap是与静态地图完全独立的对象。

指针版本没有此问题,因为将类型推荐为指针,因此复制的唯一内容是指针值本身,该值总是指向相同的(静态)对象。