C + + Initialization

Source: Internet
Author: User

Consider the following code:

int Main () {     int1;      int y = (1);//useless     int1  };           int A;  No initializer,     no consideration of int B (1);      int 1  }; }

Dazzled by the initialization syntax. With the initializer, the basic is: =1 (1) ={1} or {1} in several cases. The delimiter for the variable name and initializer is: = () {} These three kinds of

#include <iostream>classS { Public: S (std::initializer_list<int>il) {std::cout<<"S (std::initializer_list<int> il) called"<<Std::endl; } S (inti) {std::cout<<"S (int i) called"<<Std::endl; }};intMain () {S y=1; S Z= {1 }; S A (1); S b{1 }; }

We found that for user-defined types, with the {} initializer, the first match s (std::initializer_list<int> il). This is a wake-up call, {} is not so versatile initialization syntax. If you want to invoke the constructor of S (int), be honest with the traditional S-a (1) syntax.

#include <boost/type_index.hpp>#include<iostream>intMain () {Auto x= (1); Auto y=1; Auto Z= {1 }; Auto A (1); Auto b{1 }; usingBOOST::TYPEINDEX::TYPE_ID_WITH_CVR; Std::cout<< type_id_with_cvr< decltype (x) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< decltype (y) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< decltype (z) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< Decltype (a) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< Decltype (b) > (). Pretty_name () <<'\ n';}

Auto uses a different rule, ={1} will be deduced as Std::initializer_list<int>{1} and {1} will be deduced as (int) 1

Summary: Basic type int: ={1} {1} deduced into (int) 1

Custom type: ={1} {1} deduced to Std::initializer_list<int>{1} Note: The custom type constructor has a constructor that is std::initializer_list as a parameter, as defined by S.

Case of Auto: ={1} deduced into Std::initializer_list<int>{1}

{1} deduced as (int) 1

The rules are still complicated and difficult to remember, so it's good to be careful when you encounter the {} initializer.

C + + Initialization

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.