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 variablea.Instead, you want this:
If the function does not need to mutate the pointer, pass it either by const-reference or by value.