Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ about generic initialization in templates

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?

like image 329
Abruzzo Forte e Gentile Avatar asked Jun 19 '14 09:06

Abruzzo Forte e Gentile


People also ask

How can templates be used for generic programming?

Generics can be implemented in C++ using Templates. Template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need sort() for different data types.

What are generic templates?

The generic template is a simple structured message that includes a title, subtitle, image, and up to three buttons. You may also specify a default_action object that sets a URL that will be opened in the Messenger webview when the template is tapped.

Is template a generic class?

Generics and templates are both language features that provide support for parameterized types. However, they are different and have different uses. This topic provides an overview of the many differences.

What is a generic class class template?

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function.


1 Answers

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{};
like image 180
juanchopanza Avatar answered Sep 18 '22 09:09

juanchopanza