传参积分提升

Pass-by-reference and integral promotion

为什么编译器无法将 char 提升为 int&,但在通过常量引用传递它时没有问题(charint const& )?

示例代码:

#include <iostream>
using namespace std;

void func1(int & i)       { cout << "int &       " << i << endl; }
void func2(int const & i) { cout << "const int & " << i << endl; }

int main() {

    char mychar = 'a';
    func1(mychar);    // compiler-error
    func2(mychar);    // no error

    return 0;
}

促销和转化会创建一个新的临时对象。非常量引用不能绑定到临时对象。

这是允许的:

char c = 'X';
const int& i = c;

我们隐式地将 c 提升为 int 并将 i 绑定到该临时文件。这不会真正导致任何令人困惑的行为。 ic 具有相同的值,只是类型不同。

但是如果 non-const:

允许相同的逻辑会发生什么
char c = 'X';
int& i = c;
i = 'J';

i 不能直接绑定到 c - 这是错误的类型。我们仍然需要将 c 提升到 int 并将 i 绑定到那个临时的。但是当我们分配 i 时,我们只是在修改我们绑定的那个临时值 - c 仍然是 X。这将令人难以置信的混乱、不直观且容易出错。所以语言禁止它。