c++ - Uniform initialization in C++0x, when to use () instead of {}? -


Anyone using thumb to decide on using old syntax () What is the rule?

{Mykles (int px, int p): x (px), y (pi } {} Pvt: int x, y; }; ... myclass object {0}; In the case of vector as an example, there are many constructors in it whenever I do the following:

  vector & Lt; Double & gt; Number {10};  

I get a vector of element 1 as one of the 10 elements:

Clear vector (size_ type n, const T & amp; value = T (), conform noise & amp; = allocation ()); My suspicion is that whenever a class defines a initializer list constructor in the case of a vector, it should be { } syntax.

So, I'm thinking right. I.e. Will I return the old syntax only when a class defines an initial list creator to call another constructor? e.g. To correct the above code:

  vector & lt; Double & gt; Number (10); Value = 10  

I've found with just one element / 10 element 10 The answer in the standard document is hopefully, I will try to explain what I think.

First of all, if a class initialization defines the list constructor, then it is also used when it is appropriate:

§ 8.5.4 (Page 203)

Initial list constructors are placed in the list-initial (13.3.1.7) in favor of other constructors.

I think this is a great feature, eliminating the headache associated with the non-uniform style):

Then Also, the only catch (which is my question) is that if you design a class without the initial creator, then you can add it later, you can get amazing results.

Basically, the idea of ​​ std :: vector is not the initial list maker, then a vector containing 10 elements will be created in the following:

  Std :: vector & lt; Int & gt; Number {10};  

By adding an inventor list constructor, the compiler will keep its side on the other constructor due to the {} syntax. This behavior will be because the init-list constructor uses init- The elements of list <10} are are accepted. If there is no acceptable conversion, then any other constructor will be used, eg:

  std :: vector & lt; String & gt; Vec {10}; // One vector // Simple constructor of 10 elements was used because "{0}" // has not been accepted as in-list type string.  

Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

jquery - SimpleModal Confirm fails to submit form -

php - Multiple Select with Explode: only returns the word "Array" -