初始化智能指针

发布于 2025-01-02 03:43:43 字数 443 浏览 2 评论 0原文

可能的重复:
在类型名称后面添加括号与 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尝蛊 2025-01-09 03:43:43

智能指针在这里没有任何区别。两个智能指针都以相同的方式初始化,指针指向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 how X is initialized. If there is a difference and what the difference is depends on how X is defined. This answer has an excellent description of what happens in different cases. In this case since X has a default constructor they get initialized the same. However if there were no default constructor they would be initialized differently.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文