gpt4 book ai didi

c++ - `new` 运算符是否总是调用构造函数?

转载 作者:太空狗 更新时间:2023-10-29 20:34:09 25 4
gpt4 key购买 nike

我的问题受到 Thomas Cormen 教授对他的 Quora answer第二条评论的影响。 $.

他说构造函数执行以下三个任务:

  1. Allocates memory for the object.

  2. Initializes the instance variables of the object, e.g., by implicitly calling init in Python. (I also emphasize that the init method should initialize not some, but all of the instance variables.)

  3. Returns a reference to (i.e., address of) the object.

然而,MSDN documentation对于 C++* 表示它是 new 操作符:

Allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object.

我的问题是,谁是对的?或者,是否还有更多内容,比如 new 运算符总是调用构造函数,正如帖子中的评论所建议的那样?

谢谢。

$ 不幸的是,Quora 没有复制评论链接的选项 - 我只能这样做才能获得答案。
* 虽然我说的是 C++,但我认为其他语言(如 Java 和 C#)也是如此(尽管我不是 100% 确定)。

最佳答案

如果您在链接的 MSDN 页面上搜索 constructor,它是这样的:

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.

换句话说,如果存在构造函数,则调用构造函数。如果不存在,则不调用。

关于c++ - `new` 运算符是否总是调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50397514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com