Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a non-reference as a reference, without temp variable

Tags:

c++

reference

gcc

I am trying to do the following: call a function which takes references as parameters without passing "variables", just values. Shouldn't my compiler(gcc) be able to make temporary "variables" to send in? It would seem that mvc does it, one way or another (other person in project uses it).

I have:

foo(Vector&,Vector&)

Whenever I try to call foo(Vector(1,2,3),Vector(4,5,6)) I get no matching function for call to foo(Vector,Vector); note: candidates are foo(Vector&,Vector&)

What should I do? Why doesn't it work? Is there some concept I do not comprehend?

Thanks.

like image 799
Manux Avatar asked Apr 12 '26 09:04

Manux


2 Answers

Vector(1,2,3) creates a temporary, and a temporary cannot be bound to non-const reference!

So make the parameters const as:

void foo(const Vector&, const Vector&)

Now it'll work!

like image 76
Nawaz Avatar answered Apr 13 '26 21:04

Nawaz


You need to pass as const reference:

foo(const Vector&,const Vector&)

non-const references can be bound only to l-values, temporary is not a l-value.

like image 32
Suma Avatar answered Apr 13 '26 21:04

Suma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!