繁体   English   中英

通过引用/指针返回静态局部变量

[英]return by reference/pointer of a static local variable

如果我通过引用获取静态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();

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

将静态地图分配给本地变量时,无意间将其复制了。 在:

auto theMap = MyTestClass::getMap();

auto推导为std::unordered_map<int, int> ,而不是std::unordered_map<int, int>& ,这导致新对象从返回的引用中被复制初始化。 因此, theMap是与静态地图完全独立的对象。

指针版本不存在此问题,因为类型被推导为指针,因此唯一要复制的是指针值本身,该指针值始终指向同一(静态)对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM