用指针作为参数函数 - 该函数通过调用期望如何



我看到了这个示例:

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;
}

如果我调用函数通过value,它是否应该期望类似"& p"而不是p?

无论如何,通过逐个值都搞砸了,当呼叫完成并且内存泄漏时,传递给该功能的值将丢失。这是法律规范,这是没有用的。如果不使用参考或函数返回值,则该函数需要进行指针到点(实际上,编译器可能会为指针到点对点和参考点案例产生相同的代码 - 禁止插入插入 - 使用参考只是有点清洁):

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

最新更新