Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ passing a value by reference that is created in the function call (inline)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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); }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading