Base on this artical, http://www.drdobbs.com/cpp/when-is-it-safe-to-move-an-object-instea/240156579#disqus_thread
Following code will NOT call the move constructor:
void func()
{
Thing t;
work_on(t);
// never using t variable again ...
}
Following code will call the move constructor:
work_on(Thing());
The reason is for the first code snippet, the constructor may save the constructing object address, and use it later.
My question is: But for the second code snippet, the temp object still are alive before work_on finished base on the C++ standard, so the author can also save the address of the constructing object, and use it inside work_on function. So base on the same reason, it also shouldn't call move constructor, doesn't this make sense?
You got all your reasons wrong. There's nothing about "saving addresses". (Anyone can write any manner of horribly broken code by randomly storing addresses. That's not an argument.)
The simple reason is that in the first snippet, t
continues living and can be used, so you can't move from it:
Thing t;
work_on(t);
t.x = 12;
foo(t);
In the second snippet, though, the temporary value Thing()
only lives on that one line, till the end of the full-expression, so nobody can possibly refer to that value after the end of the statement. Thus it's perfectly safe to move from (i.e. mutate) the object.