what is the difference between string& and const string& ?

what is the difference between string& and const string& ?

1
2
3
4
5
        const string& f("hello");
        cout<<f;
        string& A ("hello");//Err
        cout<<A;
   
Last edited on
string& is a reference to a string while const string& is a reference to a const string i.e. a string that cannot be changed. So the question is why does f() work but A() doesn't and for that we first need to investigate the nature of the expressions of these functions' parameter.

Let's start by considering the string "hello" by itself; which one of the following is valid?

1
2
3
4
5
//Option 1:
string s = "hello";
//Option 2:
string s; 
"hello" = s; 


Obviously Option 1 because you can't assign just any string s to "hello" as "hello" is ... well ... just "hello"!

So "hello" is an r-value i.e. it can only appear on the right-hand side of an assignment statement. So now that we have established that the functions' parameter is a r-value expression, let's return to our original functions:

f() : f() is the string class constructor that returns a reference to a const string i.e. it promises not the change the argument passed to it and, as we've seen, "hello" cannot be changed (i.e. assigned to on the left hand side) as it is a r-value. So f() works.

A() however makes no such promise about not changing the argument passed to it since it's not const qualified. Hence A() doesn't work.

One way to make A() work is to use plain old string A("Hello") because in that case a COPY of "Hello" is passed to the function.

Another way to make A() work, post C++11 is to use move semantics i.e. string A(move("Hello")) by transfering the contents of "hello" without doing a copy. This is particulary useful when copying is expensive or cannot be done as in the case of unique_ptr

Topic archived. No new replies allowed.