Home > Enterprise >  Understanding const reference returned from a function
Understanding const reference returned from a function

Time:02-14

I have a function

const std::string& getRecordingJobToken() { return getToken(); }
const std::string& getToken() const { return m_Token;  }
std::string m_Token;

I am able to call it as below

const std::string jobToken = getRecordingJobToken();

However when I do this,

const std::string jobToken;
jobToken = getRecordingJobToken();

It throws me this error -

error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive]

What is the difference ? I know that a reference variable has to be initialized immediately.

std::string &ref = a;

Is it some similiar logic ? The reason i am confused is that though getRecordingJobToken() returns a const reference, the variable jobToken that I have is not a reference variable. It is a variable that is used to take a string reference being returned from the getRecordingJobToken() function.

CodePudding user response:

Initialization and assignment are different things. jobToken is const, it could be initialized, e.g.

const std::string jobToken = getRecordingJobToken(); // copy-initialization

but can't be assigned (modified) later, e.g.

const std::string jobToken;        // default-initialization
jobToken = getRecordingJobToken(); // fails; assignment

CodePudding user response:

I am able to call it as below

const std::string jobToken = getRecordingJobToken();

However when I do this,

const std::string jobToken;
jobToken = getRecordingJobToken();

error ...

Yes, you can initialize a const object (which is what you do in the first example), but you can't assign to it/change it afterwards (which is what you try doing in the second example).

Note that you don't have to though. The function getRecordingJobToken() returns a const std::string& which is "cheap" with regards to resources. It's just a refrence to an internal std::string that the class or function keeps - but doesn't let anyone modify from the outside. If you only need to read the value, take it by const reference instead:

const std::string& jobToken = getRecordingJobToken();

If you on the other hand would like to modify the returned value, take it by value (and get a copy of whatever is returned). Your jobToken does not need to be const in this situation:

std::string jobToken = getRecordingJobToken();
jobToken  = "foo"; // ok now since it's not `const`
  •  Tags:  
  • c
  • Related