它如何工作,测试* pObj = new Test();作为构造函数不返回任何东西 [英] How does it work, Test *pObj = new Test(); as constructor does not return anything

查看:106
本文介绍了它如何工作,测试* pObj = new Test();作为构造函数不返回任何东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c ++上更好。
我有一个Test类和下面的代码在main()。

  Test * pObj = new Test 

如果我们一步一个指令调试,首先它去新功能分配内存,然后它调用构造函数。然后它回到main()函数。我们都知道,构造函数不返回任何东西。在这种情况下,pObj将如何具有由新分配的指针?

当你使用新 c> expression编译器生成代码来分配内存,然后在分配的内存上调用构造函数来创建一个新对象。如果成功,则返回指向新对象的指针。



构造函数没有返回值,编译器只是在需要的内存块上添加对构造函数的调用要构建的新对象。构造函数不需要返回对象的位置,代码已经在对象必须在哪里;它(有效地)将传递给构造函数。


I am trying to get better at c++. I have a Test class and below code in main().

Test *pObj = new Test();

If we debug by steping one by one instruction, First it goes to new function to allocate memory, then it calls constructor. Then it comes back to main() function. As we all know, constructor does not return anything. In that case, how come pObj will have the pointer which is allocated by new ? Any idea how it is implemented by compiler ?

解决方案

When you use a new expression the compiler generates code to allocate memory and then call the constructor on the allocated memory to create a new object. If successful, it returns a pointer to the new object.

Constructors have no return values, the compiler just adds a call to the constructor on a piece of memory where it needs the new object to be constructed. It's not necessary for the constructor to return the location of the object, the code already knews where the object must be; it (effectively) passed it to the constructor.

这篇关于它如何工作,测试* pObj = new Test();作为构造函数不返回任何东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆