开发者

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 isn't a pointer that needs dereferencing, it's a reference and the syntax is the same as if you're dealing with a plain old 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜