different types of initialization in C++

前端 未结 2 1635
夕颜
夕颜 2020-12-10 03:02

I\'m learning C++, and am rather confused as to the different types of initialization.

You can do:

T a;

which, as far as I can tell

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 03:16

    You made a few mistakes. I'll clear them up.

    // Bog-standard declaration.
    // Initialisation rules are a bit complex.
    T a;
    
    
    // WRONG - this declares a function.
    T a();
    
    // Bog-standard declaration, with constructor arguments.
    // (*)
    T a(1, 2, 3... args);
    
    // Bog-standard declaration, with *one* constructor argument
    // (and only if there's a matching, _non-explicit_ constructor).
    // (**)
    T a = 1;
    
    // Uses aggregate initialisation, inherited from C.
    // Not always possible; depends on layout of T.
    T a = {1, 2, 3, 4, 5, 6};
    
    // Invoking C++0x initializer-list constructor.
    T a{1, 2, 3, 4, 5, 6};
    
    // This is actually two things.
    // First you create a [nameless] rvalue with three
    // constructor arguments (*), then you copy-construct
    // a [named] T from it (**).
    T a = T(1, 2, 3);
    
    // Heap allocation, the result of which gets stored
    // in a pointer.
    T* a = new T(1, 2, 3);
    
    // Heap allocation without constructor arguments.
    T* a = new T;
    

提交回复
热议问题