对于函数参数为非常量时,如果使用{}创建无名对象,该无名对象被创建为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;
};