简体   繁体   中英

What's the difference between these two local variables?

const std::string  s1("foo");
const std::string& s2("foo");

Not sure how they are different but I'm seeing evidence of both usages. Any ideas?

const std::string s1("foo");

This declares a named std::string object as a local variable.

const std::string& s1("foo");

This declares a const reference to a std::string object. An unnamed, temporary std::string object is created with the contents "foo" and the reference is bound to that temporary object. The temporary object will exist until the reference goes out of scope.

In this particular case, there is no observable difference between the two: in both cases you end up with a std::string that can be accessed via the name s1 and which will be destroyed when s1 goes out of scope.

However, in some cases, there is a difference. Consider, for example, a function that returns by reference:

const std::string& get_reference_to_string();

If you initialize s1 with the result of calling this function, there is a difference between:

const std::string s1(get_reference_to_string());
const std::string& s1(get_reference_to_string());

In the first case, a copy of the referenced string is made and used to initialize s1 . In the second case, s1 is simply bound to the std::string to which the returned reference refers: no copy is made.

They are identical in meaning, due to the way constant references can bind to temporaries plus string having an implicit conversion from char*.

For clarity and readability, prefer the non-reference.

The first instance creates a constant string variable initialized to hold "foo". The second one creates a constant reference to a string and then initializes that constant reference to point at a temporary string that was initialized to hold "foo".

const std::string s1("foo"); creates a std::string object on the stack and initializes it with the const char* string "foo." const std::string& s1("foo") , on the other hand, is a const reference to an implicitly constructed std::string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM