C ++: const refers to a local object

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

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

Thanks.

+4
source share
2 answers

Yes, s2 is legal. s2 is tied to a temporary std :: string - an extension of the temporary lifetime. s1 is not temporary, it is a named variable.

See 12.2 / 5:

The second context is when the link is tied to a temporary one. Temporary to which the link is attached, or temporary, which is the full object to the subobject, is temporary associated with preserving the lifetime of the link, except as indicated below.

+10
source

Both are legal.
S1 is a variable of type std :: String with the qualifier const.
S2 is a constant. Reference to the temporary type std :: string.

+3
source

Source: https://habr.com/ru/post/1347725/


All Articles