开发者

What is the difference between `new` and `new()` for a struct in C/C++? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Do the parentheses after the type name make a difference with new?

In some code, I recently saw a struct like this:

typedef struct MyStruct {
    int numberOne;
    int numberTwo;
} MYSTRUCT;

Later, I tried instantiating one of these structs using

MyStruct *pStruct = new MyStruct();

which worked fine with Visual Studio 2010, but failed with an obscure linker error on a different compiler. It took a 开发者_如何学Cwhile until we found out that omitting the braces like this

MyStruct *pStruct = new MyStruct;

solved the issue.

So, what exactly is the difference between these two invocations and which one is the right one to use?


new MyStruct performs default initialization, which in your case does nothing.

new MyStruct() performs value initialization, which in your case sets both int variables to zero.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜