C/C++ 中结构体的 `new` 和 `new()` 有什么区别?
可能的重复:
在类型名称后面添加括号与 new 有区别吗?
在某些代码中,我最近看到了这样的结构:
typedef struct MyStruct {
int numberOne;
int numberTwo;
} MYSTRUCT;
后来,我尝试使用它实例化这些结构之一,
MyStruct *pStruct = new MyStruct();
该结构在 Visual Studio 2010 中运行良好,但在不同的编译器上出现模糊链接器错误而失败。我们花了一段时间才发现像这样省略大括号
MyStruct *pStruct = new MyStruct;
就可以解决问题。
那么,这两种调用到底有什么区别,哪一种更适合使用呢?
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 while 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
new MyStruct
执行默认初始化,在您的情况下,它什么也不做。new MyStruct()
执行值初始化,在您的情况下,这会将两个 int 变量设置为零。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.