Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ why is constructor in this example called twice?

I just try to understand the behaviour of the following situation:

template <typename T1>
struct A{
    template <typename T2>
    A(T2 val){
        cout<<"sizeof(T1): "<<sizeof(T1)<<" sizeof(T2): "<<sizeof(T2)<<endl;
    }
    T1 dummyField;
};

so - the class is templated with T1 and the constructor is templated with T2

now - if i write:

A<bool> a = A<bool>(true);

the output is as expected:

sizeof(T1): 1 sizeof(T2): 1

however - if i write:

A<bool> a = A<float>(3.5f);

the output is:

sizeof(T1): 4 sizeof(T2): 4
sizeof(T1): 1 sizeof(T2): 4

why is the constructor called twice with template parameter float?

thanks for satisfying my curiosity

like image 570
genesys Avatar asked Jan 08 '10 12:01

genesys


1 Answers

How to avoid copying?

In both cases two constructors are called, however you do not see it in the first case as one of them is the compiler generated one. If you want to avoid copying, you need to use a different syntax, like this:

A<bool> a(true);

A<bool> a(3.5f);

Why (and what) copy constructor is called?

A<bool> a = A<bool>(true);

Here the A (bool val) constructor is used to construct the temporary value, while default compiler generated copy constructor is used to perform the copy of A to A. You are copying the same type, and for same type copy constructor is used. The interesting and not obvious fact here is: Template constructor is never used as a copy constructor, even if it looks like one.

A<bool> a = A<float>(3.5f);

Here A<float>(float val) constructor is used first to construct the temporary value, and then A<bool>( A<float> val) templated constructor is used to perform the copy.

like image 83
Suma Avatar answered Sep 24 '22 13:09

Suma