NPS
NPS

Reputation: 6355

Does VS optimize casting to the same type?

int a = (int)5;

Does VS optimize that (remove the cast)? The situation above is trivial but I'm writing some template classes which take arbitrary type arguments in constructor:

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

In most cases the cast is needed to avoid compiler warnings but when T = U then the cast is redundant. Or maybe is there a better way to implement that?

Upvotes: 2

Views: 272

Answers (1)

masoud
masoud

Reputation: 56479

Following Oded's hint from comments, I did a test in gcc-4.7.2 and 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 assembly code (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 assembly code(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)
!}

They are same in gcc.

assign1 assembly code(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 assembly code(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 

They are same in MSVC, too.

So, both compilers omit the cast.

Upvotes: 2

Related Questions