I have this example:
#include <string> #include <iostream> class Test { private: std::string str; public: Test(std::string &&str_) : str(str_) {} const std::string &GetStr() { return str; } }; int main(int argc, char *argv[]) { std::string there("1234567890"); std::cout << "1. there: " << there << '\n'; Test t1(std::move(there)); std::cout << "2. there: " << there << '\n'; std::cout << "3. there: " << t1.GetStr() << '\n'; }
He outputs
$ ./a.out 1. there: 1234567890 2. there: 1234567890 3. there: 1234567890
This uses gcc 5.1.1 for linux. Although the string there remains in a valid but undefined state after the move, this implementation seems to move (rather than copy) the string if the move constructor std :: string is called.
if I replaced the initializer str(str_) with str(std::move(str_)) , I get this output:
$ ./a.out 1. there: 1234567890 2. there: 3. there: 1234567890
This suggests that the std :: string move constructor is now used, but why isn't std::string(std::string &&) called in my first example?
c ++
binary01
source share