Basically the title. I saw a c++ program use string& somewhere, but don't know why it uses that instead of string. I tried to Google it but google ignores the & sign. What is the difference between string and string&?
Asked
Active
Viewed 909 times
1
-
Just FYI, this search engine lets you search symbols: http://symbolhound.com/ – General Grievance Sep 07 '21 at 17:16
-
For more detail you probably have to show a minimal example of code you are talking about. With that said this will likely be a duplicate but duplicates are not always easy to find. – drescherjm Sep 07 '21 at 17:19
-
When passing a string to a function, std::string& is more like std::string* in the sense that the string won't be copied. But unlike a pointer (*) it is never allowed to be a nullptr. It MUST point to (refer to) an instance. Thus it is called a reference. If you pass a std::string to a function it will be copied so that changing it won't have side effects. If you want to avoid copying AND avoid changes you use a const reference and pass the string like (const std::string& st) – Pepijn Kramer Sep 07 '21 at 17:24
-
1This happens a lot with C and C++ and is one of the reasons I recommend learning the fundamentals of a programming language from books. The Internet is helpful later after you know the terminology and how to tell the ravings of a madman from a good quality program. – user4581301 Sep 07 '21 at 17:24
2 Answers
3
The data type string& literally means “a reference to a string object.”
There are 3 things how can the & be meaned:
- Reference declaration/parameter.
- Address-of operator.
- Bitwise And operator.
Check a question ampersand (&) at the end of variable etc

Martin
- 628
- 1
- 9
- 28
-
4What do you mean "whose contents will not be changed"? I don't see a `const` anywhere. – Nathan Pierson Sep 07 '21 at 17:16
-
-
You should also mention what happens when `std::string&` versus `std::string` in function parameters. Most of the time I see `std::string7` its with function parameters. – Thomas Matthews Sep 07 '21 at 20:26
1
&string is a reference to the string object whereas the string is the object.

The Acturial Kid
- 232
- 1
- 10
-
I thought `std::string&` is a reference to a string and `std::string * p = &string_variable;` is the address of the string. – Thomas Matthews Sep 07 '21 at 20:27