草庐IT

c++ - 铿锵错误 : non-const lvalue reference cannot bind to incompatible temporary

coder 2024-02-10 原文

我有一段代码可以在 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;

和 clang 提示

non-const lvalue reference cannot bind to incompatible temporary

我有点了解正在创建一个临时文件,但不确定如何解决这个问题。有什么想法吗?

最佳答案

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

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

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

auto refInstance = m_map.find(key);

关于c++ - 铿锵错误 : non-const lvalue reference cannot bind to incompatible temporary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22997433/

有关c++ - 铿锵错误 : non-const lvalue reference cannot bind to incompatible temporary的更多相关文章

随机推荐