I want to understand why C++20 complains when I try do the following, perhaps someone can help.
I have a method defined, like so:
void doStuff(Point& dest) {
...
}
When I try to do the following:
doStuff(Point(x,y));
I get the error: C++ initial value of reference to non-const must be an lvalue
This goes away when I make Point& dest -> const Point& dest or if I define a new variable for the Point(x,y) however in the case that I do not want to defined dest as a const or I dont need a variable, why is it that the compiler complains about this? There are cases where I want to pass it in as a reference and others where I want to keep it inline with the function call to keep things more straight forward. Obviously the example I gave here is really simple, but you get the idea.
Of note I know that I can cast it like so:
doStuff(static_cast<Point&>(Point()));
But this seems really unnecessary, I’d like to find a way to achieve this without all the other nonsense. Any help is most appreciated! I might be missing something really obvious, I am no C++ expert.
>Solution :
you can accept (overload with) rvalue references void doStuff(Point&& dest)
side note: you can pass it directly to lvalue reference version if that’s what you want.
void doStuff(Point& dest);
void doStuff(Point&& dest) { doStuff(dest); }