为什么构造总会有相同的名称,类别以及它​​们是如何隐含调用? [英] Why constructors will always have same name as of class and how they are invoked implicitly?

查看:88
本文介绍了为什么构造总会有相同的名称,类别以及它​​们是如何隐含调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,为什么构造函数的名称总是相同的类名,以及如何当我们创建该类的对象其得到隐含调用。任何人都可以请解释在这样的情况下执行的流程?


解决方案

  

我想知道,为什么构造函数的名称始终作为类名

的同

由于此语法并不需要任何新的关键字。除此之外,没有很好的理由。


  

要尽量减少新的关键字数量,我没有使用明确的语法如下:

 类X {
    构造函数();
    析构函数();
}


  
  

相反,我选择了镜像的使用声明语法构造的

 类X {
    X();
    〜X();

这可能是过于聪明。 [设计与演化C ++,3.11.2构造函数符号]




  

任何人都可以请解释在这样的情况下执行的流程?


的对象的生命周期可以概括如下:


  1. 分配内存

  2. 调用构造函数

  3. 使用对象

  4. 调用析构函数/终结

  5. 释放内存

在Java中,第1步总是从堆中分配。在C#中,类是从堆中分配为好,而对于结构的内存已经可以(在非本地捕获结构的情况下,或者在他们的父对象/关闭堆栈上)。 注意,知道这些细节是一般不需要或非常有帮助。在C ++中,内存分配是极其复杂的,所以我不会详谈这里。

步骤5取决于内存是如何分配的。栈内存自动只要方法结​​束释放。在Java和C#,堆内存隐式垃圾收集器在某个未知的时间释放不再需要之后。在C ++中,堆内存在技术上是通过调用删除公布。在现代C ++中,删除很少手动调用。相反,你应该使用RAII对象,如的std :: string的的std ::矢量< T> 的std :: shared_ptr的< T> 是采取照顾自己

I want to know that why the name of constructor is always same as that of class name and how its get invoked implicitly when we create object of that class. Can anyone please explain the flow of execution in such situation?

解决方案

I want to know that why the name of constructor is always same as that of class name

Because this syntax does not require any new keywords. Aside from that, there is no good reason.

To minimize the number of new keywords, I didn't use an explicit syntax like this:

class X {
    constructor();
    destructor();
}

Instead, I chose a declaration syntax that mirrored the use of constructors.

class X {
    X();
    ~X();

This may have been overly clever. [The Design And Evolution Of C++, 3.11.2 Constructor Notation]


Can anyone please explain the flow of execution in such situation?

The lifetime of an object can be summarized like this:

  1. allocate memory
  2. call constructor
  3. use object
  4. call destructor/finalizer
  5. release memory

In Java, step 1 always allocates from the heap. In C#, classes are allocated from the heap as well, whereas the memory for structs is already available (either on the stack in the case of non-captured local structs or within their parent object/closure). Note that knowing these details is generally not necessary or very helpful. In C++, memory allocation is extremely complicated, so I won't go into the details here.

Step 5 depends on how the memory was allocated. Stack memory is automatically released as soon as the method ends. In Java and C#, heap memory is implicitly released by the Garbage Collector at some unknown time after it is no longer needed. In C++, heap memory is technically released by calling delete. In modern C++, delete is rarely called manually. Instead, you should use RAII objects such as std::string, std::vector<T> and std::shared_ptr<T> that take care of that themselves.

这篇关于为什么构造总会有相同的名称,类别以及它​​们是如何隐含调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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