Pregunta

I've been given a template problem where you have to make an element of type T, construct it and then add it to an array.

I'm not sure how to do the construct part.

Do we just do

T element;

or

T element = T();
¿Fue útil?

Solución

Provided your T is meant to be of a class type, I would say this version:

T element;

Is preferable as long as the element is default-constructible (and if it is not, none of the above approaches work). Using the second version:

T element = T();

Would mean to create a temporary object of type T from which element gets copy-constructed or move-constructed. Also, this won't compile if your type is not moveable.

When the element is of a fundamental type, on the other hand, T element = T() would provide value-initialization. So, for instance, when T = int, element would be zero-initialized, while in the first case it would be uninitialized.

In C++11, the best way (as suggested by mfontanini in the comments) is to use direct-initialization with uniform initialization syntax (so to prevent the compiler from parsing it as a function declaration):

T element{};

This will give you default-construction for class types and value-initialization for fundamental types.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top