[英]What arguments does new take?
C++ 中的new
会在幕后调用构造函数吗? 或者是周围的其他方式?
我看到像new MyClass(*this)
这样的代码让我很困惑,因为我不知道new
可以占用 arguments。
也许那是因为new
可以调用构造函数,因此它可以采用构造函数声明的 arguments?
MyClass(*this)
通过调用其构造函数并将*this
作为参数传递来创建MyClass
类型的 object。 把new
放在它后面意味着 object 分配在堆上而不是堆栈上。 争论的不是new
,而是MyClass
。
new
和operator new
是有区别的。 new
运算符使用隐藏operator new
function 来分配 memory,然后它还通过使用 class 名称后的参数调用其构造函数来“值初始化”object。
在您的情况下,您调用new
,它使用::operator new()
分配 memory,然后它使用带有参数*this
的构造函数初始化 memory 中的MyClass
class 的 object。
#include <iostream>
class A {
public:
int m_value;
A(int value): m_value(value){};
};
int main (){
int *a = new int;
auto cb= new A(1);
std::cout << *a << std::endl;
std::cout << b->m_value << std::endl;
printf("%02x ", *b);
}
Program returned:
0
15
0f
如您所见, a
变量的new
仅创建一个值初始化为 0 的指针。这就是为什么当我们取消引用它时我们有 0(所有位全为 0,int 大部分时间是 4 个字节,指针指向到 memory 内容 = 到 0x0000)
但是对于b
变量,我们传递参数。 如果我们查看b
object 的 memory 内容,我们可以读取0f
,这意味着它包含 15(成员值)
这不是new
的 arguments,它是构造函数 arguments。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.