开发者

Method return being assigned to variable

开发者 https://www.devze.com 2023-01-05 09:58 出处:网络
I have a method that is returning a CString and placing it into a variable, however this variable is a parameter in the method.Is there a better way to assign the return of the method into the variabl

I have a method that is returning a CString and placing it into a variable, however this variable is a parameter in the method. Is there a better way to assign the return of the method into the variable?

Example:

CString foo = 开发者_如何学JAVA"foo";
foo = MakeBar(foo);


Your code is fine. It's common (and often good practice) to write functions that don't modify their arguments. In your case, you want to overwrite foo, so you have to assign the result to itself.

This idiom is very common in other languages that have immutable strings.


Pass foo by reference into the function. In that way it's understood that it will be an input/output parameter.

void MakeBar(CString &foo)
{
  if(foo == "foo")
    foo = "bar";
}

//...


CString foo = "foo"; 
MakeBar(foo);


The question is how your MakeBar() function is typically used, how it is implemented. If there's a sizeable fraction of foo2 = MakeBar(foo1) calls, then it's better to have a return value. If you're sure that the output of MakeBar() always replaces the input, then the void MakeBar(CString &foo) form is better.

0

精彩评论

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