Home > database >  non-const lvalue reference to type 'pair<...>' cannot bind to a temporary of type &#
non-const lvalue reference to type 'pair<...>' cannot bind to a temporary of type &#

Time:09-16

I'm trying to get a reference to the emplaced item using auto& syntax, but it fails to compile with above error.

How can I get reference to emplaced item in this case?

I've attempted to use const auto& but the object seems invoking destructor on my actual app so thus it seems to be a fake reference at best.

#include <string>
#include <unordered_map>

class Connection {
   public:
     bool foo{};
};

int main() {
    std::unordered_map<std::string, Connection> connections;

    auto& [connection, inserted] = connections.try_emplace("test");
}

CodePudding user response:

That's because try_emplace returns a pair<iterator, bool>, which is a temporary, NOT a reference to the inserted element. See description on cppreference

After emplacing, you could say

auto& elem = connections["test"];

or

auto [connection, inserted] = connections.try_emplace("test");
auto& elem = *connection;

for example, to get a reference to the element.

const auto& compiles because it is legal to declare a const reference to a temporary, but not a non-const lvalue reference.

  •  Tags:  
  • c
  • Related