7

I am writing a generic function like 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>();

This functions prints out an undefined value for variable a, while if I change the initialization into

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

I can see that the initialized value is 0 as I am expecting.

If I call T a the variable is initialized with 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 of T() that is still the default one.

I cannot understand what is the difference behind these 2 lines and the reason why this happens?

Constructor
  • 7,273
  • 2
  • 24
  • 66
Abruzzo Forte e Gentile
  • 14,423
  • 28
  • 99
  • 173

1 Answers1

14

First of all, default initiaization of built-in types such as int leaves them uninitialized. Value initialization leaves them zero-initialized. As for your example

This is a default initialization:

 T a;

This is a value initialization, using copy initialization:

 T a = T();

You are right that copies can be elided here, so this has the effect of creating a single value-initialized T object. However, it does require that T be copyable or move-copyable. This is the case with built-in types, but it is a restriction to bear in mind.

The copy initialization syntax is required because this is a function declaration:

 T a();

but C++11 allows you to value-initialize like this:

 T a{};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480