开发者

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

开发者 https://www.devze.com 2023-02-16 19:42 出处:网络
I am trying to do the following: call a function which takes references as parameters without passing \"variables\", just values.

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&)

开发者_StackOverflow

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

Thanks.


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!


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.


Use const references if you want to pass over temporary variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消