C++ extract method from statements--> return by value


Given this bit of simplified code:

std::string s{ "abc" };
s += "xyz";
auto strBody = CreateReceiptBody(pResp) + s;

... we'd like to use Extract Method to pull out the string creation to:

std::string MyClass::CreateSomeString(){
    std::string s{ "abc" };
    s += "xyz";
    return s;

However, extract method results in:
std::string s;

... with the parameter for s being declared as a string&. Yes this does avoid the cost of the copy on return, but it's not what we seek. We note it works this way for primitives (e.g. int) as well.

The extract works the way we want if the thing to extract is the RHS of an assignment, as one example:

std::string s = std::string("abc") + "def" + "xyz";

... but if a local is assigned to, it doesn't work.

Is there a way to force the issue? We tried highlighting the rhs of the local up through subsequent statements but Resharper turns of the ability to refactor at all at this point.

Let us know if this is just a dumb idea on our part.




The way it is handled in e.g. C# extract method is that it allows to select which of the local variables will be returned by the extracted function (via the "Return type" dropdown), the rest of the parameters get passes as usual by reference.

Unfortunately this logic hasn't been implemented yet for C++, so the "Return type" can only be void in your example. I've created an issue to track this - https://youtrack.jetbrains.com/issue/RSCPP-23436.

Thanks for the feedback!


thanks Igor! sounds great, I hope JetBrains can find the time to add this functionality.


Please sign in to leave a comment.