0

I am wondering the difference between these data types in C++:

  1. const std::string&
  2. std::string const&

for example: If I run this simple piece of code:

#include <iostream>

using namespace std;

int main()
{
    std::string bar = "alpha";
    const std::string &foo = bar;
    std::string const &blah = bar;
    
    std::cout<<"bar: "<<bar<<", foo: "<<foo<<", blah: "<<blah<<std::endl;
    
    bar = "gamma";
    std::cout<<"bar: "<<bar<<", foo: "<<foo<<", blah: "<<blah<<std::endl;
    

    return 0;
}

I can observe all the values getting updated if I update the original string? Also is there a method to correctly read these data types, I heard of a right to left rule but not able to apply it?

DonBaka
  • 325
  • 2
  • 14
  • foo is the reference to string constant and blah is the reference to constant string effectively meaning the same thing here. So we can not change the string using foo and blah but it can be changed by bar. – Ankur Goel Dec 28 '21 at 14:07
  • The general rule is: `const` qualifies the type to its immediate left. The exception to the general rule is: if `const` is specified first, then it qualifies the type to its immediate right. – Eljay Dec 28 '21 at 14:17

0 Answers0