Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can't I pass an Address As a Reference?

I have a function that takes a pointer as a reference argument, but I cannot pass in &my_variable to the function. The error I am receiving is cannot convert parameter from my_class* to my_class*&, using VS2010.

Why is this not allowed?

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
}
like image 960
Eric Avatar asked Dec 16 '22 05:12

Eric


2 Answers

The result of an address-of expression is an rvalue. Therefore, you cannot bind it to reference-to-nonconst.

It also makes no sense. It's like saying int a; &a = 12; Obviously you cannot change the address of the variable a.

Instead, you want this:

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

If the function does not need to mutate the pointer, pass it either by const-reference or by value.

like image 146
Kerrek SB Avatar answered Jan 03 '23 11:01

Kerrek SB


Think about situation when you write something like

void foo(bar*& ptr) {
  ptr = new bar;
}

bar b;
foo(&b);
like image 45
Hauleth Avatar answered Jan 03 '23 11:01

Hauleth