【问题标题】:clang error: non-const lvalue reference cannot bind to incompatible temporaryclang 错误:非常量左值引用不能绑定到不兼容的临时
【发布时间】:2014-04-10 19:36:37
【问题描述】:

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

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

【问题讨论】:

    标签: c++ compiler-errors clang


    【解决方案1】:

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

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

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

    auto refInstance = m_map.find(key);
    

    【讨论】:

    • 旧代码:)。然后将该引用与 m_map.end() end 进行比较,以查看是否找不到密钥。
    • @randomThought 是的,但您不需要参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2022-01-01
    相关资源
    最近更新 更多