参数中的指针和引用

时间:2012-03-05 09:12:45

标签: c++ c pointers pass-by-reference

我在几个树代码中看到树类的功能同时具有*和&与节点 例如,在BST中插入一个节点就像这样

insertnode(node * &t,string value)
{
t = new node; t-> val = value 
// code to find right place in BST
}

我想知道为什么我们通常会引用指针,特别是这种情况。还请提及是否有任何其他情况,谢谢

而不是发布另一个问题。 有人也可以指出对象类的使用吗?我的意思是使用对象类的实例它是否分配了所有子类的所有内存?即int float等。

7 个答案:

答案 0 :(得分:6)

与任何其他变量一样,指针按值传递,除非您指定要通过引用传递它。

void foo(int* x)
{
   x = new int[1];
}

void goo(int*& x)
{
   x = new int[1];
}

int* x = NULL;
foo(x);
//x is NULL here, and you also have a memory leak
goo(x);
//x points to an array of 1 int

在您的情况下,您传递对指针的引用,因为您要修改原始指针。修改指针并不意味着改变它指向的值,而是改变它指向的地址。

答案 1 :(得分:3)

如果在函数中操作指针参数,则从函数返回后将不会保存指针值。但是如果通过引用传递指针,则返回后将保留引用的新地址指针:

void foo1(int* x)
{
    x = new int(2);
}

void foo2(int* &x)
{
    x = new int(3);
}
int main()
{
    int* x = new int(1);
    foo1(x);
    printf("x = %d\n", *x); // x = 1 => x is not referring to a new address after returning from foo1()
    foo2(x);
    printf("x = %d\n", *x); // x = 3 => x is referring to a new address after returning from foo2()
    return 0;
}

如果你不删除以前分配的内存,当然会有内存泄漏。

答案 2 :(得分:1)

它几乎与以下内容相同,但有点短,可能更容易在视觉上解析:

insertnode(node** t, string value)
{
  *t = new node;
  (*t)->val = value;
}

答案 3 :(得分:0)

这意味着该函数可以修改指针(即改变指向的位置)。

答案 4 :(得分:0)

通过引用传递指针使函数能够直接更改指针。在这种特殊情况下,它使指针指向新创建的node

答案 5 :(得分:0)

通过传递对指针的引用,这意味着您可以修改指针。

你有一个例子: http://msdn.microsoft.com/en-us/library/1sf8shae%28v=vs.80%29.aspx

答案 6 :(得分:0)

当你声明一个这样的函数时:

foo(node* param);

param实际上是一个通过值传递的指针。所以你有一个指针的副本..

如果您传递参数:

foo(node*& param);

你所拥有的是一个通过引用传递的指针,所以你有一个指针的别名!别名表示具有不同名称的相同指针。