【总结】cannot bind non-const lvalue reference of type ‘std::**&’ to an rvalue of type std::**

对于函数参数为非常量时,如果使用{}创建无名对象,该无名对象被创建为const类型的对象


出现如下的“不能绑定非常量的左值到 常量的右值 上”
即:将 非常量【std::pair<int, int>& p】 绑定到 常量【{10, 20}】 上,而导致的错误。
error: cannot bind non-const lvalue reference of type ‘std::pair<int, int>&’ to an rvalue of type std::pair<int, int>’

下面一段的constexpr说明创建的无名对象为常量的
In file included from /usr/include/c++/9/bits/stl_algobase.h:64,
                 from /usr/include/c++/9/bits/stl_tree.h:63,
                 from /usr/include/c++/9/map:60,
                 from const_conference.cpp:4:
/usr/include/c++/9/bits/stl_pair.h:341:12: note:   after user-defined conversion: ‘constexpr std::pair<_T1, _T2>::pair(_U1&&, _U2&&) [with _U1 = int; _U2 = int; typename std::enable_if<(std::_PCC<true, _T1, _T2>::_MoveConstructiblePair<_U1, _U2>() && std::_PCC<true, _T1, _T2>::_ImplicitlyMoveConvertiblePair<_U1, _U2>()), bool>::type <anonymous> = true; _T1 = int; _T2 = int]’
  341 |  constexpr pair(_U1&& __x, _U2&& __y)
         |                   ^~~~

#include <stdlib.h>
#include <stdio.h>

#include <map>

class A
{
public:
    A() = default;

    void func1(std::pair<int, int>& p)
    // void func1(const std::pair<int, int>& p)
    {
        printf("first:%d\n", p.first);
        printf("second:%d\n", p.second);
    };

    void FUNC()
    {
        int a = 10;
        int b = 20;
        std::pair<int, int> pa{a, b};
        // func1(pa);
        func1({10, 20});
    };
};

int main()
{
    A a;
    a.FUNC();

    return 0;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值