Cannot convert from T to T&

Aug 16, 2024 at 11:17pm
Cannot convert from T to T& as in the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
auto f(const map<string, int>& mp)
{
	auto p = find_if(mp.begin(),mp.end(), Greater_than{ 42 });
	return p;
}

void usePredicates()
{
	map<string, int> myMap
	{
		{"Jose", 30},
		{ "Javier", 62}
	};
	auto& pointer = f(myMap);  // ERROR cannot convert from '_InIt' to '_InIt&'
}


'
But when I change 'pointer' type to auto&& the error goes away!

Why?



Is there any harm in using auto&&? does f return an rvalue? is it a temporary object?
Last edited on Aug 16, 2024 at 11:27pm
Aug 17, 2024 at 8:40am
pointer is a ref and you can't assign the temp value from f to a ref. && will work when the return value is either a ref or a temp.
Aug 17, 2024 at 9:20am
It would have worked if you used const auto& on line 14.

auto& can sometimes deduce to a const reference:

1
2
const int ci = 5;
auto& r = ci; // OK 

But for literals and other rvalues it doesn't seem to be allowed:

 
auto& r = 5; // Error 
Last edited on Aug 17, 2024 at 9:22am
Aug 17, 2024 at 9:34am
Is there any harm in using auto&&? does f return an rvalue? is it a temporary object? is it destroyed upon line ending?


Last edited on Aug 17, 2024 at 9:35am
Aug 17, 2024 at 10:08am
Is there any harm in using auto&&?

No, I don't think so.

does f return an rvalue? is it a temporary object?

Yes.

is it destroyed upon line ending?

No, references that bind directly to temporaries extend the lifetime of the temporary so that it is not destroyed until the reference goes out of scope. This is true for all reference types (assuming the code compiles).

If the function had returned a reference the answer would have been different.
Last edited on Aug 17, 2024 at 10:09am
Topic archived. No new replies allowed.