C++11 Initialization List

Source: Internet
Author: User

First, preface
in C + + learning. I think everyone has been tortured by the definition and affirmation of variables, such as the few companies I have written in college. Have looked at the different permutations and combinations of const and variable types, which makes you different. Anti-learning C + + process has been tortured, and today to see the next part of the "glorious history." Take a look at the code first:
    Player PA;                              (a)    Player pb ();                            (b)    player pc = player ();                   (c)      player PD (player ());                    (d)        PD = Player ()                           //(E)


A,c,d is the declaration of a variable, a very easy to understand is to declare a variable, b the first feeling is to call the constructor to declare the variable. In fact, it's not, it's a function that returns the player without a number of parameters.

For C, it is called the operator= assignment operation, right? Totally not. But the gentleman became an object. Then call the player's copy constructor to generate the object PC. D and C are the same. E is the real call assignment operation. is not already by this kind of object affirmation made of dizzy head specificity. Now the C++11 initialization list is officially on.
Second, Brief introduction
Before looking at c++11 initialization, let's review the structure initialization in C language. The code is as follows:

#include <iostream>struct player{    int id;    const char* name;}; int main () {    player player = {10001, "C + +"};    printf ("%d,%s\n", Player.id, Player.name);}

struct variables are easy to initialize with a list.

C++11 introduces an initialization list to initialize variables and objects.
Third, how to use

1. System built-in type

    int ia{1};                (a)    int ib = {1};             (b)       int IC (1);                (c)     int id = 1;               (d)

Very obvious. or d more in line with the habit.


    Std::vector<int> Va{1, 2, 3};          (a)    std::vector<int> vb = {1, 2, 3};       (b)        std::vector<int> VC (1, ten);            (c)       std::vector<int> vd{1, ten};            (d)  

the initialization list can compensate for the problem of just initializing the same number in C. In use C and D do not confuse.
    std::p air<int, const char*> Getplayer () {         return {10001, "C + +"};     }    Std::map<int, const char*> players = {{10001, "C + +"}, {10002, "Java"}};

You can also return the pair type. Initializing the map is possible.



2. Define your own type
For single-parameter initialization, type-matching constructors do not have to define constructors themselves.

    Player pa{};                    (a)    Player PB;                      (b)      Player pc ();                    (c)    Player PD (b);                   (d)    Player pe = b;                  (e)    Player pf = {B};                (f)



for the above several variables initialization, recommended A, assuming the constructor with a parameter, recommended B, if it is a constructor without parameters.

3, assume that you want to implement the initialization of the list constructor. copy function, assignment function, need to include initializer_list this header file.
Class Myclass{public:    MyClass (int a): A_ (a) {        std::cout << "normal initializer list\n";    }    MyClass (std::initializer_list<int> a): B_ (a) {        std::cout << "initializer list constructor\n";    }    MyClass (myclass& my) {        std::cout << "Copy constructor\n";        This->a_ = My.a_;        This->b_ = my.b_;    }    myclass& operator= (myclass& my) {        std::cout << "operator = constructor\n";        This->a_ = My.a_;        This->b_ = my.b_;        return *this;    } Private:    int a_;    Std::initializer_list<int> b_;};


This is the class that defines the class, with the initialization list constructor, to practice class-related C + + knowledge:
    MyClass Ma{1};               (a)    MyClass MB = {1, 2, 3};      (b)    MyClass MC (2);               (c)    MyClass MD = b;              (d)    MyClass Me (c);               (e)    MyClass mf{e};               (f)    auto l{2, 2, 3,3};    MyClass mh{l};               (e)    ma = MB;                     (h)



Take a look at what results each call will output, here's the answer:

Initializer List constructor

Initializer List constructor

Normal constructor list

Copy constructor

Copy constructor

Copy constructor

initializer list Constructor

operator = Constructor


Iv. Why the list needs to be initialized
1, to avoid the class declaration object confusion, differentiated treatment, for C + + Why have parentheses initialized object This said, we can Google by themselves. It seems that no matter who has made a mistake. The courage to admit mistakes or good comrades.
2, in the initialization of a number of variables convenient
3, to avoid data segmentation, because through the initialization of the list is not agreed to the implicit conversion, the relevant knowledge can be involved in my this article.

Five, matters needing attention
1. When declaring variables, use less parentheses, and the program is more readable .
2. Use initialization lists to prevent implicit conversions and reduce bugs
3. The object returned by {} is of type Const, non-convertible

C++11 Initialization List

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.