1

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&?

Bob Jiang
  • 13
  • 3
  • 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
  • 1
    This 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 Answers2

3

The data type string& literally means “a reference to a string object.”

There are 3 things how can the & be meaned:

  1. Reference declaration/parameter.
  2. Address-of operator.
  3. Bitwise And operator.

Check a question ampersand (&) at the end of variable etc

Martin
  • 628
  • 1
  • 9
  • 28
1

&string is a reference to the string object whereas the string is the object.

The Acturial Kid
  • 232
  • 1
  • 10