VS是否优化了相同类型的铸造?

时间:2013-03-31 15:42:46

标签: c++ visual-studio optimization

int a = (int)5;

VS是否优化(删除演员表)?上面的情况是微不足道的,但我正在编写一些模板类,它们在构造函数中采用任意类型的参数:

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

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

1 个答案:

答案 0 :(得分:2)

根据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中也是一样的。

因此,两个编译器都省略了演员。