是“ std :: forward”和“ std :: move”不生成代码吗?

问题描述 投票:0回答:1

“ std :: forward”和“ std :: move”不生成代码是真的吗?我在《有效的C ++ 11/14采样器》中看到了这句话。相关代码在脚注中。如果答案是肯定的,有人可以详细解释一下代码吗?对于这个问题,我将不胜感激。

根据文档(https://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a00416_source.html),其中说:

   /**
    *  @brief  Forward an lvalue.
    *  @return The parameter cast to the specified type.
    *
    *  This function is used to implement "perfect forwarding".
    */
   template<typename _Tp>
     constexpr _Tp&&
     forward(typename std::remove_reference<_Tp>::type& __t) noexcept
     { return static_cast<_Tp&&>(__t); }



  /**
    *  @brief  Forward an rvalue.
    *  @return The parameter cast to the specified type.
    *
    *  This function is used to implement "perfect forwarding".
    */
   template<typename _Tp>
     constexpr _Tp&&
     forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
     {
       static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument"
                     " substituting _Tp is an lvalue reference type");
       return static_cast<_Tp&&>(__t);
     }
    /**
    *  @brief  Convert a value to an rvalue.
    *  @param  __t  A thing of arbitrary type.
    *  @return The parameter cast to an rvalue-reference to allow moving it.
   */
   template<typename _Tp>
     constexpr typename std::remove_reference<_Tp>::type&&
     move(_Tp&& __t) noexcept
     { return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }
c++ c++11 c++14 move perfect-forwarding
1个回答
0
投票

不正确。它生成代码。代码

#include <utility>

int main() {
    int a;
    int b = std::move(a);
}

使用Clang 10.0生成此程序集(无优化):

main:                                   # @main
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        lea     rdi, [rbp - 4]
        call    std::remove_reference<int&>::type&& std::move<int&>(int&)
        xor     ecx, ecx
        mov     edx, dword ptr [rax]
        mov     dword ptr [rbp - 8], edx
        mov     eax, ecx
        add     rsp, 16
        pop     rbp
        ret
std::remove_reference<int&>::type&& std::move<int&>(int&): # @std::remove_reference<int&>::type&& std::move<int&>(int&)
        push    rbp
        mov     rbp, rsp
        mov     qword ptr [rbp - 8], rdi
        mov     rax, qword ptr [rbp - 8]
        pop     rbp
        ret

和代码

#include <utility>

int main() {
    int a;
    int b = a;
}

使用Clang 10.0生成此程序集(无优化):

main:                                   # @main
        push    rbp
        mov     rbp, rsp
        xor     eax, eax
        mov     ecx, dword ptr [rbp - 4]
        mov     dword ptr [rbp - 8], ecx
        pop     rbp
        ret

https://godbolt.org/z/DthcYe

© www.soinside.com 2019 - 2024. All rights reserved.