2

Suppose we have those two functions:

std::string foo()
{
    return "myString";
}

and

std::string goo()
{
    return std::string("myString");
}

I am thinking that in foo the string will be constructed, then copied and then returned while in the second it will be constructed and moved.

Am I correct? Or both cases are the same?

TheCrafter
  • 1,909
  • 2
  • 23
  • 44

1 Answers1

2

It depends on NRVO/RVO and c++ standard (move or copy constructor).

But both cases are the same.

In one you have implicit conversion to std::string but in second case you have explicitly created an object:

return std::string("myString");

What is (N)RVO and copy/move elision?

Community
  • 1
  • 1
VP.
  • 15,509
  • 17
  • 91
  • 161
  • Yeah but since in the first case we have the additional step of the implicit conversion, wouldn't that make the second case just a tiny bit faster? – TheCrafter Jul 19 '15 at 11:44
  • 2
    They are the same because in first case compiler will do the same as you do in second case - it will create an object by passing "myString" to it's constructor. Here is no difference. Just in second case you wrote this explicitly while in first case compiler will do that for you. – VP. Jul 19 '15 at 11:45
  • Ok got it. Thank you! – TheCrafter Jul 19 '15 at 12:09