-
July 12th, 2012, 08:12 AM
#1
Is 'operator new[]' supposed to call the default constructor on POD?
I am using VS2010 and am checking how operator new[] behaves for POD like int. The following code produces this output in a release build:
340178 340178 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Code:
#include <iostream>
int main()
{
int *in = new int[20];
std::cout << std::hex;
for ( int i = 0; i < 20; ++i )
{
std::cout << in[i] << " ";
}
std::cout << std::endl;
delete[] in;
}
In debug build, the output is
cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd cdcdcdcd
which does not surprise me.
I was thinking that operator new[] calls the default constructor int() and all values in the array should have a value of 0. Am I missing something here?
Thanks,
Richard
-
July 12th, 2012, 08:46 AM
#2
Re: Is 'operator new[]' supposed to call the default constructor on POD?
no, in an expression "new T[20]" T is default-initialized that for POD means having an unspecified value ( as in the expression "T t;" ).
What you want is called value-initialization: the syntax in the array case is "new T[20]()" ( or "new T[20]{}" in newest compilers ) ( as in "T t = T();" or "T t{};") that for POD means being zero-initialized.
Last edited by superbonzo; July 12th, 2012 at 08:50 AM.
Reason: cosmetics
-
July 12th, 2012, 09:17 AM
#3
Re: Is 'operator new[]' supposed to call the default constructor on POD?
Ah, thanks superbonzo. This works like I want it to.
The reason I asked is I have some legacy code which either uses new[] or even malloc and then sets the values to 0 or calls memset. I was thinking about a better way...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|