RVO V.S. std::move -- Zhao Wu

Discussion about the RVO optimization technique & std::move.

RVO V.S. std::move

by Zhao Wu

From the article:

To summarize, RVO is a compiler optimization technique, while std::move is just an rvalue cast, which also instructs the compiler that it's eligible to move the object. The price of moving is lower than copying but higher than RVO, so never apply std::move to local objects if they would otherwise be eligible for the RVO.

Add a Comment

Comments are closed.

Comments (6)

3 1

Ivan Le Lann said on Jul 20, 2015 02:58 AM:

Code advised in this post is returning address of local variable and is thus very crash friendly :
http://coliru.stacked-crooked.com/a/f1bd407f93230770

PS: Could not comment on blog site. "Add a Comment" link is broken for me.
1 1

kmhofmann said on Jul 20, 2015 11:23 PM:

@Ivan: Of course it is. That's why it's clearly mentioned in the blog post not to do this! It might help actually reading the post, and not just blindly running it through an online compiler. smile
0 0

Ivan Le Lann said on Jul 21, 2015 01:34 AM:

@kmhofmann

The "Don't DO THAT!" warning is for the "return value + std::move" case.
In first version published, the "return && + std:move" case was absolutely not warned.
So you had a simple "Yes! The compiler does RVO!" right after it.

A C++ beginner reading first version of this article might conclude that "return && + std:move" is the best solution ...

Regards
0 1

R. A. Berliner said on Jul 21, 2015 03:48 AM:

@kmhofmann: There is a note in the article:

"(Note: We should not use this way in the real development, because it is a reference to a local object. Here just show how to make RVO happened.)"

This note was inserted *after* I posted a comment on developerWorks pointing out the mistake, and the editor's own response confirms that he updated the article. So I think you should be careful of accusing *others* of reading difficulties.

Technically, the statement "The compiler does RVO!" is still incorrect, as a return by reference is never eligible for copy/move elision as per §12.8/31 (N3376), but I don't want to come across as a nagger…
0 0

Joel Lamotte said on Jul 21, 2015 11:27 AM:

This article seems weird indeed.
My current understanding is that

[code]
BigObject foo(int n) {
BigObject localObj;
return localObj;
}
int main() {
auto f = foo(1);
}
[/code]

Is the only correct way to either trigger RVO or get a move.
Am I correct? That's what I gathered from my different readings these last years.
1 0

Jordan Jack said on Jul 21, 2015 11:25 PM:

I think if we use gcc/clang, we can turn on the compiler option -fno-elide-constructors to see more clear result. grin