I am reading this post: What are move semantics?
Note that the example given in that post for move constructor was:
string(string&& that)
{
data = that.data;
that.data = nullptr;
}
I found it confusing when we use string a(x+y)
to construct a new string. Since the result of x+y
is a temporary variable, it gets destroyed very soon. That would mean copying over the pointer (data = that.data
) would indeed be copying over a dangling pointer, after the original data (which should be stored in the stack frame of x+y
that gets cleaned up after the function call finishes) is destroyed. It seems that setting that.data
to nullptr won't help, as the stack frame gets cleaned up anyways.
Can anyone explain why this is not an issue? And how does c++ actually handles such situations?