简体   繁体   中英

How to get the value of const string& in C++

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

string returnVal = *value

Simply do

string returnVal = value;

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

string returnVal = value;

value不是需要解除引用的指针,它是一个引用,语法与处理普通旧值的语法相同。

Since you are going to modify 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.
}

Why not just create a local variable, like so:

void foo(const std::string &value)
{
  string returnVal(value);

  // Do something with returnVal

  return returnVal;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM