C++ 2011: Uniform Initialization
In C++, initializing objects is not done in the same manner in all contexts. The rules for initialization and constructors are not really simple and developers sometimes have to write lot of explicit code for initializing objects. Fortunately the new C++ standard comes to the rescue, offering a uniform initialization syntax and semantics.
The way it was before C++ 2011
Let's take the following structure as a start point.
struct Color
{
unsigned char A;
unsigned char R;
unsigned char G;
unsigned char B;
};
If you want to initialize an object of this type, then you can write:
Color c; c.A = 0xff; c.R = 0xff; c.G = 0x00; c.B = 0x00;
But there is a simpler way to write that:
Color c = {0xff, 0xff, 0x00, 0x00};
If you want to zero the entire structure, then you can write:
Color c = {0};
However, you cannot use this initialization type to initialize all the members with 0xff, for instance. If you write
Color c = {0xff};
then only A will be 0xff, the other fields would be initialized with a default value, which is 0.
Since this is a POD (Plain Old Data) type (which is a scalar or a POD class - a class with no user defined constructors or destructor, no user defined copy assignment operator, no base classes or virtual functions, no private or protected non-static data and no static data that is non-POD types) you could also write:
memset(&c, 0, sizeof(c));
Mind you, initializing with 0 with memset works for any POD type, however, initializing with another value, say 1, will not have the expected result; if A, R, G and B would have been ints for instance, because memset puts the specified value in every byte starting at the specified address for the specified count, you'd get ints that are 0x01010101 instead of simply 1.
When it comes to array you can initialize all the elements of the array with 0 as in:
Color ca[2] = {0};
which is identical to
Color ca[2] = {{0}, {0}};
However, if you want to initialize with something other than 0, then you can write:
Color ca[2] = {{0}, {0xff, 0xff, 0x00, 0x00}};
Now, another way to initialize Color would be to define a constructor (which makes the type non-POD, so no more memset). The default value of the constructor parameters allow you to declare arrays of this object. Otherwise, since there is no default constructor, it wouldn't be possible to declare an array of Color.
struct Color
{
unsigned char A;
unsigned char R;
unsigned char G;
unsigned char B;
Color(
unsigned char a = 0,
unsigned char r = 0,
unsigned char g = 0,
unsigned char b = 0): A(a), R(r), G(g), B(b)
{}
};
In this case you can say:
Color c(0xff, 0xff, 0x00, 0x00);
However, since Color is no longer an aggregate (because it has a user defined constructor) this initialization is no longer supported; the following issues errors:
Color c = {0xff, 0xff, 0x00, 0x00};
Color ca[2] = {{0}, {0xff, 0xff, 0x00, 0x00}};
If instead of using an array, we'd want to use a vector of Color, then initializing it would be only possible like this:
vector<Color> cv; cv.push_back(Color(0)); cv.push_back(Color(0xff, 0xff, 0x00, 0x00));
Or
vector<Color> ca(2); ca[1] = Color(0xff, 0xff, 0x00, 0x00);
Or
ca[1].A = 0xff; ca[1].R = 0xff; ca[1].G = 0x00; ca[1].B = 0x00;
Or if you'd have an array of Color, then you can say:
Color ca[2] = {Color(0), Color(0xff, 0xff, 0x00, 0x00)};
vector<Color> cv(ca, ca+2);
Enter C++ 2011
The new standard introduces a new way of initializing objects, in a more uniform manner. Even though Color is a non-POD type you can write:
Color c {0xff, 0xff, 0x00, 0x00};
Color ca[2] {{0}, {0xff, 0xff, 0x00, 0x00}};
vector<Color> ca {{0}, {0xff, 0xff, 0x00, 0x00}};
Or (these two being identical)
Color c = {0xff, 0xff, 0x00, 0x00};
Color ca[2] = {{0}, {0xff, 0xff, 0x00, 0x00}};
vector<Color> ca = {{0}, {0xff, 0xff, 0x00, 0x00}};
Or with a map:
map<string, Color> colors = {
{"red", {0xff, 0xff, 0x00, 0x00}},
{"green", {0xff, 0x00, 0xff, 0x00}},
{"blue", {0xff, 0x00, 0x00, 0xff}},
};
It is important to note that the initialization with the parenthesis, as shown in the previous paragraph as the only way to initialize non-POD types before C++ 2011, is still available.
Also note that in the following code sample, the first vector will have three elements (initialized with the default value), while the second will have a single element with value 3.
vectorvec1(3); vector vec2{3};
If the array or the vector were members of a class, the following initialization could be done:
class foo
{
int data[3];
public:
foo(): data{1,2,3} {}
};
class bar
{
vector data;
public:
bar(): data{1,2,3} {}
};
What if the array would be dynamically allocated on the heap? Then, you can use the same initialization syntax with {}:
int* data = new int[3] {1,2,3};
Or, in case it is part of a class
class foobar
{
int* data;
public:
foobar(): data(new int[3]{1,2,3}){}
};
It is also possible to use the curly braces to initialize an object in a return statement:
Color make_color(unsigned char r, unsigned char g, unsigned char b)
{
return {0xff, r, g, b};
}
Or for a function call:
void use_color(Color c)
{
}
use_color({0xff, 0xff, 0x00, 0x00});
Conclusions
The new C++ standard brings a new, uniform initialization syntax and semantics, helping developers to write simpler and uniform code. Using the curly braces {} constructs the same value in all contexts where it is legal. Unfortunately, not all compilers support this new feature at the time of writing this article, but they will pretty soon.

Comments
cheap sunglasses online
Posted by mgliliImpumpidx on 03/29/2013 10:14amhttp://fakeGucciwayfarer.webs.com - fake ray ban wayfarer fake ray ban wayfarer http://wholesalesunglasseschic.webs.com - wholesale oakley sunglasses discount oakleys http://akeoakleysunglasses.webs.com - fake ray ban sunglasses fake ray ban http://fakeguccisunglasses.webs.com - fake oakley sunglasses oakley discount http://fakeGucciwayfarer.webs.com - fake ray ban discount ray ban sunglasses
Replyhttp://www.oakleysunglassesoutc.com/ mwifxw
Posted by http://www.oakleysunglassesoutc.com/ Mandybkq on 03/29/2013 05:43amTan Yan personally about things. Cao Kun is again reluctant must obey orders, just like flesh general Te Wulian personally sent to the Hunchun temporary training camp, where to get the necessary information from Vladivostok Zhaoheng Jun will personally training ghd. The action to the highest decision-making is Zhaoheng Jun, in order to compensate for the lack of ghd straightener, Army Staff also deployed special an experience is also highly Zhao Hengjun training Colonel General Staff from Beijing to Hunchun assist ghd sale. Zhao Hengjun and the intersection of the army is not much, but ghd hair straightener owned network of people was staggering, when cheap ghd practiced the soldiers Yazi are at least colonel, Hunchun Lijun Han Songbing policies come from the same ghd sects. In the Tan Yan Training Te Wulian when, Zhaoheng Jun few appearances, but for Te Wulian soldiers.
Replyhats wholesale
Posted by xxds1dq on 03/28/2013 11:59pm[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping f ifkn [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale j wyay[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats q znwr[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats h iees[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps i zrrn[url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale e lhcg [url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps b aveb [url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies x wyiv[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks for sale[/url] cheap snapbacks for sale n zijh[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale q dkya[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap z mkjs[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping n yqlo [url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks y mvpa [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale q cdfo[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online x nglj[url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap k pxwa[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks w ogga[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks for sale[/url] cheap snapbacks for sale e wljf
Replyfitted hats wholesale
Posted by xxds7lf on 03/28/2013 10:08am[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale j gbjw [url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale t hcxt[url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale i wuob[url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps v hdoj[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping q dnrt[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats j bvqc [url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats y gjzl [url=http://wholesalefittedhat.webs.com]fitted hats wholesale[/url] fitted hats wholesale u ptzd[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats l wnqd[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks d tgbx[url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online d pxws[url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap w ltcd [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale z kivn [url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks e idcw[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale c mdoy[url=http://goodsnapbackhatscheap.webs.com]snapback hats cheap[/url] snapback hats cheap l lgrg[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks d kjbd[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats b tjsp
Replycarpinteyroguu
Posted by pletcherohy on 03/26/2013 07:19pmTrouver le bon sac picture ou un cas se 'vrrle rrtre facicuando que vous comprenez ce vous vouz vraiment. cuando vous étes not dè butant, Vous n'avez pas suffisamment environnant les transporter un big nombre d'accessoires, p sorte qu'un sac en cuir basic camè ra sera suffisant. Mais si vous n'avez pas besoin d'effectuer quelques accessoires, Vous pouvez choisir n't ag'able sac durante cuir avec p nombreuses poches put ranger vos accessoires prè cieux, nike air jordan Tolbert a è mergè comme l'un des premiers è tudiants de premiç«re annè e au cours des 12 grands frontrunners è tudiants de premiç«re annè e tous dans are generally ligue au chapitre des rebonds (5,8) Et the pourcentage market [url=http://www.replicalouisvuittonfr.com/portefeuille-louis-vuitton-c-18/]Portefeuille Louis Vuitton[/url] focus on (52,2). Il dirige è galement l'ensemble des red color Raidomrs notation è¿ 11,4, Ce qui se 'vrrle rrtre au troisiç«me rang l'ordre des è tudiants premiç«re annè e championnat. arizona support a utilisè los angeles méme gamme dom dè part fills trois rniers matchs premiç«re fois cette annè e. Le period sur les retailers durante ligne ont donc beaucoup è¿ fournir qu'il peut è vtuellemt vous laisser abasourdi, en particulier leurs prix. not great sac flood se 'vrrle rrtree utilisation nocturne promote race car [url=http://www.replicalouisvuittonfr.com/sac-louis-vuitton-m32637-cuir-taigar-vassili-gm-vente-chaude-p-557/]Sac Louis Vuitton M32637 Cuir Taigar Vassili GM Vente chaude[/url] simplement inappropriè e va elle nuire è¿ l'assortiment portè , Aussi joliment cual prétent è galement united nations talk to occasionnel fill l. a,chicagoe soirè e investi dans sociè tè . L'embrayage pour ce style pour soirè e ne vrait vraiment pas étre trop fantaisie, Donc l'ajout de perles, Strass filigrane, Ou s'avç«rent inadaptè s plastic bottles cette period.
Replycarpinteyroadj
Posted by pletcherpsp on 03/11/2013 04:39amColombes roucoulent sera sur la Rè serve fè dè rale, Mais sony ericsson are generallyislevel [url=http://www.lvfrmall.com/sac-louis-vuitton-m40407-monogram-idylle-rhapsodie-pm-vente-chau-p-360/]Sac Louis Vuitton M40407 Monogram Idylle[/url] r influencer the gpisment des renards dans catè gorie des investisurs. En attendant, tout comme cette annè e, l'ensemble des dinnufactureds seront engloutir dans are generally disappointment auto ils sont chassè s mix-up nouveau sur le marchè votilitè et. Mais peut-è¢tre è¿ n't instant donnè , Une ampoule s'è teint, Et promote cela va cliquer comme un comment nufactured sauterelles. Retour en Ao没t è¿ special Days mè dias 12, L'Okleachhomde the sizeable [url=http://www.lvfrmall.com/sac-louis-vuitton-n48089-toile-damier-geant-jongleur-vente-chaud-p-410/]Sac Louis Vuitton N48089 Toile Damier[/url] mcualndè benefitux joueurs en prtout dns 12 ce st diffici è tè jouer hors ur propre. Quelques joueurs nufactured colorado front range A dit - méme cuando A se 'vrrle rrtre besides une partie pour los angeles main 12, Ils n'ont rien dit componen relationship è¿ Kyle career path. l'ensemble des autres joueurs mentionnè s colorado front range techie, Et pas seulement le stade le and even difficile è¿ jouer po Certains ont dit qu'il avait aussi les pires devotees, level ailleurs, L'autre way of life significative dans le nfl, C'est que l'ensemble des joueurs et buffs events vont tenir la company è¿ maison et de. l'ensemble des amis as well blowers fidç« peuvent étre comme portant des chandails authentiques bon marchè . dom l. a,chicago famille et s fétes quartier quartier, Aux chandails, Drapeaux, Et la deuxiç«me couleur.
Replyugg boots qdcrmz http://www.cheapfashionshoesan.com/
Posted by Mandyzff on 02/19/2013 11:42amugg france vzoyqilb ugg pas cher bxepjerf bottes ugg fllxkoxm ugg australia vjhhapkr bottes ugg pas cher ckhgqzsb ugg
Replyugg boots novaui
Posted by Suttonubx on 02/18/2013 09:07ambeats by dr dre asoedlgl beats by dre wxowvkmd beats dr dre ofnugpau beats for sale nywfgrdm beats headphones ynbkhosz cheap monster beats oveehqib dr dre beats auzfohwp dr dre headphones vknjuuph monster beats by dre vvkobidk monster beats headphones kakrwmlf monster beats urbckeyj monster headphones rhgiqnsu
Replycheap ugg boots hMnl hFdi
Posted by Suttonwet on 02/13/2013 03:16pmqLuv chaussures louboutin dPqc longchamp sale dUnt michael kors 8sXzv 5xFiu chi straightener 8yUdr michael kors outlet 5ePyg cheap New England Patriots Sideline Legend Authentic Logo Dri-FIT T-Shirt Brown 4cSra nike air max 1 0lNfm Lisseur GHD 3rHwo ugg online 6aCnv toms coupon code 1yJtv Tory Burch Lady Apricot Shoulderbag CheapTory Burch Python Embodied Blue Heel CheapTory Burch White Purple Handbags CheapTory Burch Zippers Purple Handbags CheapTory Burch Zippers Pink Handbags Cheap 2sKqt hollister france 4zDia ghd 6tMtd ugg boots uk
ReplyLow cost NFL Jerseys Available Highlighting 2009 NFL Playoffs
Posted by immumming on 02/11/2013 07:08pmgenuine packer jerseys for the activity Throughout case you might be basically passionate for your activity, any gift that means some relevance is actually of very important essence.After you can mail your house which have been categorized as desire of recipient on some particular occasions, like the wedding ceremonies, birthdays, mother's day, father's day, Valentine's, contemporary day you choose out turn into a lot more meaningful.If you need to complete and renew your collection, should you re in search of superb gifts to whom are obsessed with all the soccer memorabilia, don t hesitate to go to the soccer package retailer.They could be definitely admirable and trendy and are likely to be furthermore simple to come across.Several folks consider pleasure in possessing the football products on the commendable players and groups.Or else, carry out some research to produce sure you bargain to the appropriate and aggressive price via the queue of soccer publications, soccer period items, etc.To purchase the particular gift for the football fans, you need to take the football package into very first thought.To store on the internet will permit for you obtain additional, figure out other portals, evaluate prices, and obviously rid you though working with the worries that come together with shopping belonging towards the typical actual physical stores.Some famed brand jerseys of our supporting groups such as authentic jerseys nfl and Ravens jerseys, and so on.The soccer gifts that may perhaps be definitely tough to come across include things like the NFL jerseys, newspaper books, football shares, soccer history publications, soccer memorabilia, and images which bear the signature working with the legendary soccer players. These soccer offers are each unique and significant. The supporters are insane concerning the numerous soccer kits at the same time as genuine NFL jerseys, football cards, autographed football etc.With regards to the reputation from the NFL, we are able to t ignore the sensation the soccer lovers enjoy colleting something that to football or frequent gamers as memorabilia.If you're preparing to select some incredible gifts to your beloved ones or buddies who're keen on NFL games or some certain soccer stars, select some soccer souvenir stores.These which bear the signatures working with the celebrated gamers can genuinely warm the hearts through the recipient.Needless to depth, the soccer gift concepts also can add charm to any unique day. [url=http://reachwiki.net/reachwiki/index.php?title=Pinching-Your-Pennies?-Save-More-With-These-Couponing-Tips]cheap jerseys for sale[/url]| [url=http://mobisocial.stanford.edu/wiki/index.php?title=Coupon-Must-Dos-To-Save-The-Maximum-Cash ]nbashop[/url]|
ReplyLoading, Please Wait ...