No, the compiler is not allowed. For some reason, not only because it is difficult to do. I think copying and moving can have side effects, and you need to know when you can expect each one to be used. For example, it is well known that returning a local object will move it - you expect it to be documented, this is normal.
So, we have the following features:
Your example:
void SetString(std::wstring str) { m_str = str; }
For r-values: one r-ref in str , plus a copy in m_str . For l-values: copy to str copy to m_str .
We can do this “better” manually:
void SetString( std::wstring str) { m_str = std::move(str); }
For r-values: one r-ref in str , plus a transition in m_str . For l-values: copy in str a move to m_str .
If for some reason (you want it to compile without C ++ 11 without changes, but automatically take advantage of C ++ 11 when porting the code?), You don’t want to “manually optimize” the code you can do:
void SetString(const std::wstring& str) { m_str = str; }
For r-values: one ref in str , plus a copy in m_str . For l-values: a ref in str a copy in m_str . Never copy.
source share