Search code examples
c++stdmove

When I do int a = std::move(b) (b is int also), is it same as just a = b?


When I do int a = std::move(b) (b is int also), is it same as just a = b?


Solution

  • Depends on the compiler! The assembler for the variant with std::move without optimization will try to remove the "reference" even though it is unnecessary, which the ASM code for the variant without std::move will not - this gives you a slight overhead (a call to std::move which contains a few instructions and an additional movl on the top level) in terms of CPU instructions!

    Test Code:

    Example without optimization using GCC 8.2 in X86_64 assembler:

    #include <stdio.h>
    
    int main()
    {
        c = b;
        return 0;
    }
    
    
    int alternative()
    {
        c = std::move(b);
        return 0;
    }
    

    Assembler O0:

    main:
            pushq   %rbp
            movq    %rsp, %rbp
            movl    b(%rip), %eax
            movl    %eax, c(%rip)
            movl    $0, %eax
            popq    %rbp
            ret
    
    alternative():
            pushq   %rbp
            movq    %rsp, %rbp
            movl    $b, %edi
            call    std::remove_reference<int&>::type&& std::move<int&>(int&)
            movl    (%rax), %eax
            movl    %eax, c(%rip)
            movl    $0, %eax
            popq    %rbp
            ret
    
    std::remove_reference<int&>::type&& std::move<int&>(int&):
            pushq   %rbp
            movq    %rsp, %rbp
            movq    %rdi, -8(%rbp)
            movq    -8(%rbp), %rax
            popq    %rbp
            ret
    

    However, if you turn on optimization (-O3), it really becomes the same in terms of CPU instructions:

    main:
            movl    b(%rip), %eax
            movl    %eax, c(%rip)
            xorl    %eax, %eax
            ret
    
    alternative():
            movl    b(%rip), %eax
            movl    %eax, c(%rip)
            xorl    %eax, %eax
            ret