How to get the default value of any type

后端 未结 4 1756
难免孤独
难免孤独 2021-02-08 07:47

In C# I can write something like this:

    class AnyThing
    {
        static public T Default = default(T);
    }

    static void Main ()
    {
              


        
4条回答
  •  广开言路
    2021-02-08 08:15

    Taken literaly from "The C++ Programming Language, Third Edition by Bjarne Stroustrup":

    BEGIN QUOTE

    4.9.5 Initialization [dcl.init]

    If an initializer is specified for an object, that initializer determines the initial value of an object. If no initializer is specified, a global (§4.9.4), namespace (§8.2), or local static object (§7.1.2, §10.2.4) (collectively called static objects) is initialized to 0 of the appropriate type. For example:

    int a;  // means int a=0;
    double d; // meands d=0;
    

    Local variables (sometimes called automatic objects) and objects created on the free store (sometimes called dynamic objects or heap objects) are not initialized by default. For example:

    void f()
    {
       int x;   // x does not have a well-defined value
       // . . . 
    }
    

    Members of arrays and structures are default initialized or not depending on whether the array or structure is static. User-defined types may have default initialization defined (§10.4.2).

    More complicated objects require more than one value as an initializer. This is handled by initializer lists delimited by { and } for C-style initialization of arrays (§5.2.1) and structures (§5.7).

    For user-defined types with constructors, function-style argument lists are used (§2.5.2, §10.2.3). Note that an empty pair of parentheses () in a declaration always means ‘‘function’’ (§7.1). For example:

    int a[] = {1,2};    // array initializer
    Point z(1,2);       // function-style initializer (initialization by constructor)
    int f();            // function declaration
    

    END QUOTE

    So, you can get the default value of any type form a static object of that type:

    static T defaultT; // `defaultT' has de default value of type T
    

提交回复
热议问题