different types of initialization in C++

前端 未结 2 1632
夕颜
夕颜 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;
    
    0 讨论(0)
  • 2020-12-10 03:23

    T a = 1; // implicitly converted to T sometimes?

    You can do that if T has a copy constructor.

    T a();

    this sound more like a function declaration of "a" that return a type T

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