C ++ on generic initialization in templates

I am writing a generic function as shown below.

template<class Iterator, class T> void foo(Iterator first, Iterator last) { T a; cout << a << endl; // do something with iterators } typedef vector<double>::iterator DblPtr; vector<double> values; foo< DblPtr, int>(); 

These functions print the undefined value for the variable a , and if I change the initialization to

  /// T a = T() cout << a << endl; // do something with iterators 

I see that the initialized value is 0 , as I expect.

If I call T a , the variable is initialized to the default value, but if I call T a = T() , I believe that due to optimization, the copy constructor should be called with the value T() , which is still the default value.

I can’t understand what is the difference between these two lines and why is this happening?

+7
c ++ initialization generic-programming templates function-templates
source share
1 answer

First of all, by default, initialization of built-in types such as int leaves them uninitialized. Initializing the value leaves them with zero initialization. As for your example

This is the default initialization:

  T a; 

This is initializing the value using copy initialization :

  T a = T(); 

You are correct that copies can be deleted here, so this results in the creation of a single initialized value of the T object. However, this requires T copy or move. This is the case with built-in types, but this limitation has in mind.

Copy initialization syntax is required because it is a function declaration:

  T a(); 

but C ++ 11 allows you to initialize the value as follows:

  T a{}; 
+11
source share

All Articles