Since std::string result = foo(); is an initializer, it will call the constructor, not the assignment operator. In C ++ 11 or later, there is guaranteed to be a move constructor with the prototype std::basic_string::basic_string( basic_string&& other ) noexcept . In every real-life implementation, this moves the contents, not copies them. Although I do not believe that the standard provides for a specific implementation, he says that this particular operation should be performed in constant and non-linear time, which excludes a deep copy. Since the return value of foo() is a temporary rvalue, this is the constructor that will be called in this fragment.
So yes, this code will move the line, not copy it.
The expression in the return will not always be copied. If you return std::string("SOMELONGVALUE"); (software constructor), implementations are allowed to build the result instead. If foo() returns std::string& and returns something other than temporary, which will be returned by reference. (Returning a temporary reference that was destroyed is, as you know, undefined behavior!). And some compilers, even before C11, would do the copying and not create a temporary one just for copying and destruction. This is still allowed, and your compiler may or may not be able to apply it here.
Davislor
source share