Reputation: 4385
I had the following code in VC++ 2010:
PWCHAR pszErrorMessage = new WCHAR[100];
This code initializes a char pointer to an array. But the values in the array are garbage. I wanted a way to set the values to zero. Changing the above to the one below sets all the values in the array to zero. This works for arrays of custom structures too.
PWCHAR pszErrorMessage = new WCHAR[100]();
Upvotes: 1
Views: 610
Reputation: 490728
As noted elsewhere, yes, the parentheses force value initialization, which means arithmetic types will be initialized to zero (and pointers to null pointers, etc.) For types that explicitly define default constructors that initialize the members, this won't make any difference--for them, the default constructor will be invoked whether the parentheses are included or not.
Yes, this can have some (minor) performance implication: initializing the memory can take some time, especially if you're allocating a large amount. It doesn't always though: if you were allocating an object type with a default ctor that initialized its members, then that ctor would be used either way.
This feature was added in the C++03 standard. Offhand, I don't recall whether it was implemented in VC++ 2005 or not. I tried to do a quick scan through the VC++ developers blog, but that post-dates the release of VC++ 2005. It does include some information about VC++ 2005 SP1, which doesn't seem to mention it.
At least when I've looked at the code produced, the code to zero the allocated buffer seemed to be allocated in-line, at least for simple types like char
and such. For example:
xor eax, eax
mov rcx, QWORD PTR $T86268[rsp]
rep stosb
Upvotes: 1