Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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<...> &&).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading