Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ construction: "MyClass c" is bad, "MyClass c = MyClass()" is slow, I want "MyClass c()"
    text
    copied!<p>Here's some code:</p> <pre><code>class MyClass { public: int y; }; int main() { MyClass item1; MyClass item2 = MyClass(); } </code></pre> <p>When I run this, I receive the following values:</p> <pre><code>item1.y == [garbage] item2.y == 0 </code></pre> <p>Which, well, surprises me.</p> <p>I expected item1 to be default-constructed and item2 to be copy-constructed off an anonymous default-constructed instance of MyClass, resulting in both equaling 0 (since default-constructors initialize members to default values). Examining the assembly:</p> <pre><code>//MyClass item1; //MyClass item2 = MyClass(); xor eax,eax mov dword ptr [ebp-128h],eax mov ecx,dword ptr [ebp-128h] mov dword ptr [item2],ecx </code></pre> <p>Shows item2 being constructed by writing a '0' value somewhere temporary and then copying it into item2, as expected. However, there's NO assembly for item1. </p> <p>So, the program has memory for item1 in the stack but it never <em>constructs</em> item1.</p> <p>I can appreciate wanting that behavior for speed purposes, but I want the best of both worlds! I want to know item1.y == 0 (it gets constructed), but I don't want to waste time on default-construct-anonymous-instance-then-copy-construct like item2 does. </p> <p>Frustratingly, I can't force a default-construct by saying <code>MyClass item1();</code> since that is interpreted as a function prototype. </p> <p>So... if I want to use the default constructor on item1 without also copy-constructing, how the heck do I do that?</p> <p>Side-note: it looks like if I declare a constructor for MyClass, item1 is constructed as usual. So this behavior only applies to compiler-generated constructors.</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