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.