CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    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

  2. #2
    Join Date
    Oct 2008
    Posts
    1,456

    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

  3. #3
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    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
  •  





Click Here to Expand Forum to Full Width

Featured