简体   繁体   English

C ++参考返回

[英]C++ reference return

In this example 在这个例子中

class Object {
  Object(int val);
}


std::map<unsigned, Object> myMap;
Class Foo {

    Object &getObject (unsigned Id, int val) {

    auto pair = myMap.emplace(std::piecewise_construct, std::forward_as_tuple(Id), std::forward_as_tuple(val));
    if (pair.second) {
      // do something
    }
    else {
      // do another
    }
    return pair.first->second;
  }

}

is the returned reference in the pair (destroyed outsize the function) stay valid ? 该对中返回的引用(销毁了该函数)是否保持有效?

Yes it stays valid. 是的,它仍然有效。

emplace returns a std::pair with first being an iterator to the inserted element and second being a bool stating if the emplace was successful. emplace返回一个std::pairfirst一个是插入元素的迭代器, secondbool说明该放置是否成功。

If you're sure that second is true then the iterator in first is pointing to the element inside the map and thus taking a reference of that object will work. 如果您确定secondtruefirst的迭代器指向映射内的元素,因此可以对该对象进行引用。

Just make sure myMap outlives any getObject() calls of course. 只需确保myMap任何getObject()调用myMap

只要myMap的范围是全局的,该引用将始终有效,即,它不会指向垃圾,而是指向标准地图中的实际元素。

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

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