当我执行 int a = std::move(b)(b 也是 int)时,它与 a = b 相同吗?

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

当我做 int a = std::move(b)(b 也是 int)时,它和 a = b 一样吗?

取决于编译器! std::move 没有优化的变体的汇编器将尝试删除 "reference" 即使它是不必要的,没有 std::move 的变体的 ASM 代码不会 - 这给你一点CPU 指令的开销(对 std::move 的调用,其中包含一些指令和顶层的附加 movl)!

测试代码:

在 X86_64 汇编程序中使用 GCC 8.2 进行优化的示例:

#include <stdio.h>

int main()
{
    c = b;
    return 0;
}


int alternative()
{
    c = std::move(b);
    return 0;
}

汇编器 O0:

main:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    b(%rip), %eax
        movl    %eax, c(%rip)
        movl    [=11=], %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    [=11=], %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

但是,如果你开启优化(-O3),就CPU指令而言,它真的变得一样了:

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