指针作为参数的函数 - 函数通过调用期望什么?

时间:2017-12-11 19:09:56

标签: c++ pointers

我看到了这个例子:

void pass_by_value(int* p)
{
//Allocate memory for int and store the address in p
p = new int;
}

void pass_by_reference(int*& p)
{
p = new int;
}

int main()
{
int* p1 = NULL;
int* p2 = NULL;

pass_by_value(p1); //p1 will still be NULL after this call
pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory

return 0;
}

如果我调用函数pass-by-value,它不应该期望类似"& p"而不是p?

1 个答案:

答案 0 :(得分:1)

无论如何,pass-by-value都会搞砸,当调用完成并且内存泄漏时,传递给函数的值将会丢失。它的法律代码,它只是无用的。如果不使用引用或函数返回值,函数将需要采用指向指针的指针(实际上,编译器可能为指针指针和引用指针的情况生成相同的代码 - 禁止内联 - 使用参考只是更清洁一点):

void foo(int ** p)
{
    *p = new int;
}

int main()
{
    int * p = nullptr;
    foo(&p);
    delete p;
}