Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : const reference to local object

Tags:

c++

const std::string s1 = "abc";
const std::string & s2 = "abc";

Is the definition of s2 legal? If so, what is the difference between between s1 and s2?

Thanks.

like image 474
pic11 Avatar asked Dec 13 '22 14:12

pic11


1 Answers

Yes, s2 is legal. s2 is bound to a temporary std::string - extending the temporaries lifetime. s1 isn't a temporary, it's a named variable.

See 12.2/5:

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below.

like image 97
Erik Avatar answered Dec 26 '22 11:12

Erik