are these assignments to temporary valid?

Aug 2, 2024 at 7:30pm
Hi,

I have this code where I am not sure the assignments are valid:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int g(double x) { return std::floor(x); }

double& h(double x) { return x; } 	// return lvalue reference

double&& i(double x) { return g(x); } // return rvalue reference

void callG() {
	auto ag = g(8.8);		// ag  == int    (makes a COPY)
	auto ah = h(8.8);		// ah  == double (makes a COPY)
	auto ai = i(8.8);		// ai  == double (makes a COPY)
	//auto& lg = g(8.8);	        // lg  == int& BUT ERROR!!!	(reference to temporary variable)- cannot convert from int to int&
	auto& lh = h(8.8);		// lh  == double&
	//auto& li = i(8.8);		// li  == double&	ERROR!!! (reference to temporary variable)- cannot convert from double to double&

	auto&& rg = g(8.8);		// rg  == int&&
	auto&& rh = h(8.8);		// rh  == double&		
	auto&& ri = i(8.8);		// ri  == double&&

	decltype(auto) dg = g(8.8);	// dg == int
	decltype(auto) dh = h(8.8);	// dh == double&
	decltype(auto) di = i(8.8);	// di == double&&
}


Does variable ri extend the life of the temporary it receives? Can we use ri?

what about di? about rg?

If they can't be used what is their purpose or reason for existing?

Thanks!
Last edited on Aug 2, 2024 at 8:47pm
Aug 3, 2024 at 8:18am
h and i return dangling references. All big compilers (GCC, Clang and MSVC) warn about this by default.

Only ag, rg, and dg are safe to use.
Last edited on Aug 3, 2024 at 9:07am
Topic archived. No new replies allowed.