Well, aside from that reason, since the type of these parameters is templated, you don't know how
expensive it is to copy the actual parameter onto the stack. For simple ints, indeed the const reference
will be very slightly slower than if the formal parameter were just a value. For things like std::string
or an STL container, it could take a long time to copy the entire container onto the stack. When
writing a generic class like this, it is best to assume worst case and pass by const reference (const
to document to your user the fact that the constructor will not be modifying the argument).
Setting that aside. Creating generic templates is not easy. Your template makes a couple of
additional requirements on T_1 and T_2 that it does not need to make. For example, the
implementation of your constructor mandates that T_1 and T_2 both be default constructible
and assignable. Now, assignable may not be too bad, considering that at best they will have
to be copyable, and objects that are copyable are usually (but not always) assignable. But
the default constructible is not only annoying, but could incur a runtime penalty if default
construction is expensive.
A better way to write the constructor is to use initializer lists:
1 2 3
|
CTemplateClass( const T_1& p1, const T_2& p2 ) :
param_1( p1 ), param_2( p2 )
{}
| |
In calling my version of the constructor, T_1's copy constructor will be invoked exactly
once, and T_2's copy constructor will be invoked exactly once.
In calling your version of the constructor, T_1's default constructor will be invoked once,
then T_2's default constructor once, then T_1's assignment operator once, then T_2's
assignment operator once.