为什么我不能将地址作为参考传递?

时间:2012-01-09 20:28:26

标签: c++ compiler-errors

我有一个函数将指针作为引用参数,但是我无法将&my_variable传递给函数。我收到的错误是cannot convert parameter from my_class* to my_class*&,使用VS2010。

为什么不允许这样做?

class my_class
{
public:
    my_class();
    my_class(my_class* &parent);
};

-

int main()
{
    my_class a;
    my_class b(&a);                   // Not legal

    // ---
    my_class a;
    my_class* a_ptr = &a;
    my_class b(a);                    // Legal

    // ---
    my_class* a = new my_class;
    my_class* b = new my_class(a);    // Legal
}

3 个答案:

答案 0 :(得分:10)

表达式地址的结果是右值。因此,您无法将其绑定到引用到非对象。

这也没有意义。这就像说int a; &a = 12;显然你不能改变变量a的地址。

相反,你想要这个:

int a;
int * p = &a;
mutate_me(p);    // declared as mutate_me(int * &);

如果函数需要改变指针,则通过const-reference或value传递它。

答案 1 :(得分:1)

当你写

之类的东西时想一想情况
void foo(bar*& ptr) {
  ptr = new bar;
}

bar b;
foo(&b);

答案 2 :(得分:1)

非正式地,通过引用期望参数的方法期望它被传递到可以合法地放置在赋值语句左侧的东西(有时称为“左值”)。

int main()
{
    my_class a;
    my_class b(&a);                   // Not legal: &a = 0; would be illegal because you can't change an address of a variable.

    // ---
    my_class a;
    my_class* a_ptr = &a;
    my_class b(a_ptr);                    // Legal: You've declared a_ptr on the stack and its value (what it points to) can be changed. The address of a_ptr would not be changeable though.

    // ---
    my_class* a = new my_class;
    my_class* b = new my_class(a);    // Legal: Again, this is on the stack and `a` could point to something else, but its own address won't be changed.
}

在这种情况下,值得指出的是,在大多数情况下,按值传递指针是便宜的并且可以工作。如果你真的需要指针可修改(通过引用传递),那么你需要传递一个左值。

另一个选择是引用为const。然后我相信你可以通过rvalues就好了。

相关问题