Why can't I pass the address as a link?

I have a function that takes a pointer as a reference argument, but I cannot pass the function &my_variable function. The error I get 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 } 
+4
source share
3 answers

The result of the address expression is an rvalue. Therefore, you cannot bind it to a nonconst binding.

It is also pointless. This is how to say int a; &a = 12; int a; &a = 12; Obviously, you cannot change the address of the variable a .

Instead, you want:

 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.

+10
source

Think about a situation when you write something like

 void foo(bar*& ptr) { ptr = new bar; } bar b; foo(&b); 
+1
source

Informally, a method that expects a parameter by reference assumes that it is passed something that can be legally placed on the left side of the assignment operator (sometimes called an "lvalue").

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

In this case, it is worth noting that in most cases, passing a pointer by value is inexpensive and will work. If you really need a pointer to modify (passed by reference), you need to pass an lvalue.

Another option is to have a const link. Then I believe that you can just pass rvalues .

+1
source

Source: https://habr.com/ru/post/1390111/


All Articles