简体   繁体   中英

C++ move constructor for a class with string member

I've wrote a class with following code:

class Test {
public:
...
    Test( const Test &&that ) : i(that.i), s(std::move(that.s)) {
        cout << "move contructor." << endl;
    }
...
private:
    int i;
    std::string s;
};

if I disassemble the generated code I see:

        .type   Test::Test(Test const&&), @function
Test::Test(Test const&&):
...
       call    std::remove_reference<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&>::type&& std::move<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
        movq    %rax, %rsi
        movq    %rbx, %rdi
.LEHB3:
        call    std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)@PLT

it surprises me the call to basic_string<...>::basic_string( basic_string<...> const&) because I expected a call to the move constructor of the basic_string basic_string<...>::basic_string( basic_string<...> &&) .

I'm implementing in a incorrect way the move constructor ?

Rvalue references to const types aren't very useful. They say that code can steal from the object, but must do so without changing its value?

Since std::string doesn't have a string(const string&&) move constructor, overload resolution can only use the string(const string&) copy constructor.

A normal move constructor doesn't use the const :

Test( Test &&that ) : i(that.i), s(std::move(that.s)) {
    std::cout << "move constructor." << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM