开发者

What does "return obj(value); return?

What does return obj(value);ret开发者_如何学Gourn? Returns it the newly constructed object or a copy of it?

The reason why I am asking: Is

return obj(value);

more efficient than

temp = obj(value); 
return temp;

?

Follow-up: If so, is it really a difference, or do compilers optimize this away?


Return statement always returns a copy of the argument object with one exception: when the function returns a reference, the reference might be attached to the argument of return directly, in which case no copy is made, of course.

For this reason, from the pedantic point of view in your case there's no way to say what happens, since we don't know the signature of the function in which your return is used. Does it return a reference or not?

If we assume that the function returns a non-reference type (and that is probably what you implied), then, again, a copy is returned in both cases. In the second case you also yourself make an extra copy in temp object. So, from the abstract point of view, the second variant makes one extra copy and therefore is "slower". However, C++ language allows rather far-reaching optimizations in cases like that. Read about RVO (return value optimization) and NRVO (named return value optimization). Because of these optimizations it is actually possible that both variants will produce the same code and, obviously, will be equally efficient.

In the end it boils down to the code your specific compiler will be able to generate. If you want to know which is faster either time it with your specific compiler and with your specific compiler settings. Or inspect the generated machine code.


It isn't more efficient. It return a new created value as a copy. But in both cases it's possible that the compiler optimize the return value.


What does return obj(value);return?

An obj.

Returns it the newly constructed object or a copy of it?

Depends on the compiler.

more efficient than

No.

However, once we add optimizations to the compiler the story can change. NRVO and RVO are different optimizations. The compiler can apply one and not the other.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜