什么时候应该传递"T*const&"类型的指针?

iam*_*ind 4 c++ pointers const pass-by-reference

T*&当我打算更改函数内的指向值时,我会传递指针:

void foo(char *&p)
{
  p = (b == true)? new char[10] : 0;
}
Run Code Online (Sandbox Code Playgroud)

但我无法得到T* const&指针类型的用例(因为该指针不可更改)?我的意思是为什么我不能简单地通过T* const

void foo(char* const &p);  // p is not changeable
void foo(char* const p);   // p is not changeable
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 10

T* const &如果指针对象的值可能被函数外部的某些内容更改,并且您希望能够观察指针对象值的更改,或者您希望存储引用或指针,则可以使用a 作为参数指针对象供以后阅读.

一个T*参数(相当于T* const一个函数参数)只是给你一个指针对象的副本,它是传递给你的函数时它的值的快照.

void foo( char* const& ptr )
{
    char* p1 = ptr; // initial value
    global_fn();    // ptr might be changed
    char* p2 = ptr; // new value of ptr
}
Run Code Online (Sandbox Code Playgroud)

VS

void foo2( char* ptr )
{
    char* p1 = ptr; // initial value
    global_fn();    // ptr can't be changed, it's local to this function
    char* p2 = ptr; // will be the same as p1
}
Run Code Online (Sandbox Code Playgroud)

从技术上讲,即使函数本身也可能改变传递给引用的指针的值.

例如

char* p;

std::ptrdiff_t foo( char* const& ptr )
{
    ++p;
    return p - ptr; // returns 0, would return 1 if the parameter was by value
}

int main()
{
    char test[] = "Hello, world!";
    p = test;
    foo( p );
}
Run Code Online (Sandbox Code Playgroud)