简体   繁体   中英

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.

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.

Just make sure myMap outlives any getObject() calls of course.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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