Note that there are some explanatory texts on larger screens.

plurals
  1. POC-style initialization lists in C++, structs, and class constructors
    text
    copied!<p>I'm still on the road to enlightenment in C++, so bear with me...</p> <p>Suppose I have a struct:</p> <pre><code>struct MyThing { int a, b; }; </code></pre> <p>I fancy creating one using the c-style shorthand, Fig.1:</p> <pre><code>MyThing mt = { 1, 2 }; </code></pre> <p>Then suppose I decide to stick a method somewhere in my struct, and (being the kind of person that I am) I feel structs don't really suit methods, so turn it into a class:</p> <pre><code>class MyThing { public: int a, b; int sum() { return a + b; } }; </code></pre> <p>My Fig.1 still works fine - everything's hunky dory. Then I decide I'll eventually need a private method and member:</p> <pre><code>class MyThing { private: int c; void swap() { c = a; a = b; b = c; } public: int a, b; int sum() { return a + b; } }; </code></pre> <p>At this point, the c-style initialization list in Fig.1 fails to compile (in VS anyway) with "non-aggregates cannot be initialized with initializer list" - which is nicely explained here: <a href="http://msdn.microsoft.com/en-us/library/0s6730bb(v=vs.71).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/0s6730bb(v=vs.71).aspx</a></p> <p>So I switch to:</p> <pre><code>class MyThing { private: void swap() { int c = a; a = b; b = c; } public: int a, b; MyThing (int _a, int _b) : a(_a), b(_b) {} int sum() { return a + b; } }; </code></pre> <p>then change Fig.1 to (Fig.2)</p> <pre><code>MyThing mt(1, 2); </code></pre> <p>Sooooo, after all that, my question is: is there any benefit of using c-style initialization lists (i.e. are they faster?) for creating things? Or would it do just as well in the first place to have:</p> <pre><code>struct MyThing { int a, b; MyThing(int _a, int _b) : a(_a), b(_b) {} }; </code></pre> <p>And use it as fig.2 from the beginning? Is there any performance hit at all (even if it's negligible)?</p> <p>Thank you!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload