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
}
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.
Think about situation when you write something like
void foo(bar*& ptr) {
ptr = new bar;
}
bar b;
foo(&b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With