clang错误:非常量左值引用无法绑定到不兼容的临时

clang error: non-const lvalue reference cannot bind to incompatible temporary

本文关键字:绑定 不兼容 引用 错误 非常 常量 clang      更新时间:2023-10-16

我有一段代码可以很好地使用MSVC,但无法使用clang++进行编译

void MyCass::someMethod()
{
   std::wstring key(...);
   auto& refInstance = m_map.find(key); // error here
}

其中m_map被定义为

std::map<const std::wstring, std::shared_ptr<IInterface>> m_map;

叮当声抱怨

non-const lvalue reference cannot bind to incompatible temporary

我有点理解正在创建一个临时的,但不知道如何解决这个问题。有什么想法吗?

右值不能绑定到非常量引用。MSVC有一个"允许这样做的扩展。要符合标准,你需要

const auto& refInstance = m_map.find(key);

但这会返回一个迭代器。使用对迭代器的引用是不常见的。数值很好:

auto refInstance = m_map.find(key);