I'm writing a template class and at one point in my code would like to be able to value-initialize an object of the parameterized type on the stack. Right now, I'm accomplishing this by writing something to this effect:
template <typename T> void MyClass<T>::doSomething() { T valueInitialized = T(); /* ... */ } This code works, but (unless the compiler is smart) it requires an unnecessary creation and destruction of the temporary T object. What I'd like to write is the following, which I know is incorrect:
template <typename T> void MyClass<T>::doSomething() { T valueInitialized(); // WRONG: This is a prototype! /* ... */ } My question is whether there is a nice way to value-initialize the automatic object without having to explicitly construct a temporary object and assign it over to the automatic object. Can this be done? Or is T var = T(); as good as it gets?
Tis a user-defined type, it should have a default constructor. If it's an intrinsic type, the performance loss from copy-constructing should be negligible. Even that's assuming that the compiler won't optimize it away.T var = T();syntax and figured that there was probably a cleaner way to do it. You're completely correct that the performance hit should be negligible.