Yol*_*ola 4 c++ pointers const reference
void f(char * & pch) {
cout << &pch << " " << pch << endl;
}
int main() {
char *pch2 = new char[11];
strcpy(pch2, "1234567890");
cout << &pch2 << " " << pch2 << endl;
f(pch2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出下一个输出:
0xbfa0d62c 1234567890
0xbfa0d62c 1234567890
Run Code Online (Sandbox Code Playgroud)
但如果我按如下方式修改第一行
void f(char const * const & pch) {
Run Code Online (Sandbox Code Playgroud)
我会得到:
0xbfec7df8 1234567890
0xbfec7dfc 1234567890
Run Code Online (Sandbox Code Playgroud)
是因为需要将新的内存单元标记为const或其他东西而出现的指针差异?
pch2是一个char*,而不是一个char const*.您不能将类型的引用绑定到类型char const*&的指针char*,因此以下内容将是格式错误的:
char* p(0);
char const*& r(p);
Run Code Online (Sandbox Code Playgroud)
类似地,如果您的函数被声明为void f(char const*& pch),则char*由于const限定符不匹配,您将无法使用参数调用它.
您的示例工作的原因是const引用可以绑定到临时,并且编译器可以构造char*指针的临时副本,为临时指定类型char const*,并绑定pch对该临时指针的引用.