Here's some code:
class MyClass
{
public:
int y;
};
int main()
{
MyClass item1;
MyClass item2 = MyClass();
}
When I run this, I receive the following values:
item1.y == [garbage]
item2.y == 0
Which, well, surprises me.
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:
//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
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.
So, the program has memory for item1 in the stack but it never constructs item1.
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.
Frustratingly, I can't force a default-construct by saying MyClass item1();
since that is interpreted as a function prototype.
So... if I want to use the default constructor on item1 without also copy-constructing, how the heck do I do that?
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.