The following uses copy-initialization, which is 'probably fine' 95% of the time in C++03:
T var = T();
But for generic (C++03) code, you should always prefer direct-initialization to account for that other 5%:
T var((T())); // extra parentheses avoid the most vexing parse – the extra parentheses
// force the contents to be evaluated as an expression, thus implicitly
// *not* as a declaration.
Or better yet, use the Boost.Utility.ValueInit library, which packages up the ideal behavior for you along with workarounds for various compiler deficiencies (sadly, more than one might think):
boost::value_initialized<T> var;
For C++11, one can use list-initialization syntax to achieve direct value-initialization in a significantly less noisy/ugly manner:
T var{}; // unambiguously value-initialization?
(?N.b. technically this will invoke std::initializer_list<>
constructors instead of performing value-initialization for certain pathological types. Presumably the net result should be the same.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…