【问题标题】:Does VS optimize casting to the same type?VS 是否优化转换为相同类型?
【发布时间】:2013-04-01 00:10:29
【问题描述】:
int a = (int)5;

VS 是否对此进行了优化(移除演员表)?上面的情况很简单,但我正在编写一些模板类,它们在构造函数中采用任意类型参数:

template <typename U>
MyClass(U argument)
{
    T a = (T)argument;
}

在大多数情况下,需要强制转换以避免编译器警告,但是当 T = U 时,强制转换是多余的。或者也许有更好的方法来实现它?

【问题讨论】:

  • 写下来,编译它并查看IL(使用ILDASM或像Reflector这样的反编译器)。
  • 如果您需要演员表,请使用 c++ 演员表而不是 c 风格的演员表。在 c++ 中,当您使用 (T)x 时,编译器实际上会尝试使用预定义的 C++ 强制转换集,它实际上可能最终使用 reinterpret_cast
  • 如果你真的很担心,你仍然可以包含&lt;type_traits&gt; 并写一些类似T a = std::is_same&lt;T,U&gt;::value ? arg : (U) arg; 的东西——虽然老实说这有点傻。
  • @Damon 我唯一可能“担心”的是演员阵容的开销。您的解决方案不会增加不同的(但仍然是)开销吗?
  • 编译输出中没有演员表;不可能。想一想:在 C++ 中,将使用的强制转换必须在编译时确定,并且编译器必须同时具有操作数和结果的类型。编译器使用这些类型来选择它需要输出的确切操作。一旦编译器决定您要求从intint 的静态转换,编译器就没有什么可做的了。不存在将int 转换为int 的代码片段。

标签: c++ visual-studio optimization


【解决方案1】:

根据 cmets 的 Oded 提示,我在 gcc-4.7.2 和 MVSC-2012 中进行了测试:

template <typename U, typename T>
void assign1(const T& t, U &u)
{
    u = (U) t; // CAST
}

template <typename U, typename T>
void assign2(const T& t, U &u)
{
    u = t;    // WITHOUT CAST
}

int main()
{
    {
        int t = 12;
        int u = 1;
        assign1(t, u);
    }
    {
        int t = 12;
        int u = 1;
        assign2(t, u);
    }
}

assign1 汇编代码(gcc):

!{
!    u = (U) t;
assign1<int, int>(int const&, int&)+3: mov    0x8(%ebp),%eax
assign1<int, int>(int const&, int&)+6: mov    (%eax),%edx
assign1<int, int>(int const&, int&)+8: mov    0xc(%ebp),%eax
assign1<int, int>(int const&, int&)+11: mov    %edx,(%eax)
!}

assign2 汇编代码(gcc):

!{
!    u = t;
assign2<int, int>(int const&, int&)+3: mov    0x8(%ebp),%eax
assign2<int, int>(int const&, int&)+6: mov    (%eax),%edx
assign2<int, int>(int const&, int&)+8: mov    0xc(%ebp),%eax
assign2<int, int>(int const&, int&)+11: mov    %edx,(%eax)
!}

它们在 gcc 中是相同的。

assign1 汇编代码(MSVC):

001413EE  mov         eax,dword ptr [u]  
001413F1  mov         ecx,dword ptr [t]  
001413F4  mov         edx,dword ptr [ecx]  
001413F6  mov         dword ptr [eax],edx  

assign2 汇编代码(MSVC):

0014142E  mov         eax,dword ptr [u]  
00141431  mov         ecx,dword ptr [t]  
00141434  mov         edx,dword ptr [ecx]  
00141436  mov         dword ptr [eax],edx 

它们在 MSVC 中也是一样的。

因此,两个编译器都省略了强制转换。

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多