What is the difference between `new` and `new()` for a struct in C/C++? [duplicate]
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.
精彩评论