初始化智能指针
可能的重复:
在类型名称后面添加括号与 new 有区别吗?
以下初始化有什么区别?在本教程中,情况与#1 相同,但是如果我使用下面的#2 方法,会有什么区别吗?
struct X
{
X() {}
int x;
};
int main()
{
std::auto_ptr<X> p1(new X); // #1
std::auto_ptr<X> p2(new X()); // #2
}
Possible Duplicate:
Do the parentheses after the type name make a difference with new?
Whats the difference between the following initialisations? In the tutorial, it is as in case #1 but does it make any difference if i use the #2 way below?
struct X
{
X() {}
int x;
};
int main()
{
std::auto_ptr<X> p1(new X); // #1
std::auto_ptr<X> p2(new X()); // #2
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
智能指针在这里没有任何区别。两个智能指针都以相同的方式初始化,指针指向
X
。不同之处在于X
的初始化方式。是否存在差异以及差异是什么取决于X
的定义方式。 这个答案很好地描述了不同情况下发生的情况。在这种情况下,由于X
有一个默认构造函数,因此它们的初始化方式相同。但是,如果没有默认构造函数,它们的初始化方式将会有所不同。The smart pointer doesn't make any difference here. Both smart pointers are initialized in the same way, with a pointer to
X
. The difference is howX
is initialized. If there is a difference and what the difference is depends on howX
is defined. This answer has an excellent description of what happens in different cases. In this case sinceX
has a default constructor they get initialized the same. However if there were no default constructor they would be initialized differently.