2
int a = (int)5;

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

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

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

4

1 回答 1

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

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

于 2013-03-31T16:01:48.950 回答