How to get const string & in C ++ value

I have a function that takes a const string & value as an argument. I am trying to get the value of this string so that I can manipulate it in this function. Therefore, I want to store the value in a string returnVal , but this does not work:

string returnVal = *value

+4
source share
4 answers

Just do

 string returnVal = value; 

Since the value is not a pointer, but a reference, you do not need a pointer-dereference operator (otherwise it will be const string * value).

+6
source
 string returnVal = value; 

The value is not a pointer that needs dereferencing, it is a reference, and the syntax is the same as if you were dealing with a plain old value.

+2
source

Since you're going to change the string anyway, why not just pass it by value?

 void foo(std::string s) { // Now you can read from s and write to s in any way you want. // The client will not notice since you are working with an independent copy. } 
+1
source

Why not just create a local variable, for example:

 void foo(const std::string &value) { string returnVal(value); // Do something with returnVal return returnVal; } 
0
source

Source: https://habr.com/ru/post/1339839/


All Articles