gcnew T vs gcnew T()

I was asked recently, why I always do gcnew T() when gcnew T produces the exact same MSIL. Here’s why. In standard C++, new T and new T() are not the same. The latter version zeroes out the memory before calling the constructor, so if you haven’t initialized a member variable, it’s zero initialized by default. To be safe, I always did new T() even though it incurred some extra lines of code. To be consistent in syntax, I chose to do the same with gcnew too, even though for both cases, the CLR zeroes out the memory before invoking a call to the constructor.

[MOD]Just a note to add that the difference is applicable only to POD types. See my comment on this.[/MOD]

Advertisements

6 thoughts on “gcnew T vs gcnew T()

  1. Thank you for sharing this! I have programmed in C++ for years, but never know the difference between new T and new T(). I did a quick search of MSDN and my c++ books on my desk after reading your article, but still can not find where this is mentioned. Can you tell me how did you learn this?
    Thank you very much.

  2. Hello Yawl

    It’s part of the C++ standard, and I believe it’s been so for a while now. Note that, the difference is applicable only for POD types. For non-POD types, new T and new T() are the same.

  3. Hey Jambo

    POD = Plain Old Data

    Typically, when you say POD, you mean native types like int or char, or simple classes that do not have virtual functions, user defined constructors etc.

  4. Hi Nish,

    I tried this by creating one sample, but I didnt see the difference. Can you explain little more specific.

    class meminit
    {

    public:
    int i;
    float f;
    meminit()
    {

    i = 2;
    f = 4;
    }
    };

    int main(int argc, char* argv[])
    {

    meminit* t2, *t3;

    t2 = new meminit;
    t3 = new meminit();
    }

    thank in advance !!!

  5. There´s at least one constructor declared in the class. Compiler asumes you want to initialize those members, so it does not touch them. Otherwise compiler zeroes t3 data.

    Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s