Value-initializing an automatic object?

前端 未结 3 1818
北荒
北荒 2020-12-06 04:14

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 accomp

相关标签:
3条回答
  • 2020-12-06 04:41

    No, there isn't any other way to reliably value-initialize a template type in C++03.

    If you can count on T only being class types with default constructors, you could just write

    T valueInitialized;
    

    but if T might as well be a built-in type,

    T valueInitialized = T();
    

    is the way to go.

    Do you have any reason to not to trust your compiler to optimize away that copy?

    0 讨论(0)
  • 2020-12-06 05:01

    You can use curly braces in C++0x:

    T valueInitialized{};
    
    0 讨论(0)
  • 2020-12-06 05:02

    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.)

    0 讨论(0)
提交回复
热议问题