析构函数c+_了解C ++中的析构函数

析构函数c+

In this tutorial, we are going to understand the concept of destructors in C++, their uses as well as try to implement them in our code.

在本教程中,我们将了解C ++中析构函数的概念,它们的用法以及尝试在我们的代码中实现它们。

C ++中的析构函数是什么? (What are the Destructors in C++?)

Theoretically, a Destructor is a member function that is used to destroy or delete an object. It can be user-defined. But if not defined, by default at the time of compilation the compiler generates an inline destructor.

从理论上讲, 析构函数是用于破坏或删除对象的成员函数。 可以是用户定义的。 但是,如果未定义,默认情况下在编译时,编译器会生成一个内联析构函数。

A destructor is invoked automatically when the object goes out of scope or is explicitly destroyed by the delete operator.

当对象超出范围或由delete运算符明确销毁时,析构函数将自动调用。

Now let us look at the syntax of defining a destructor in C++ for a class named example:

现在让我们来看一下在C ++中为名为example的类定义析构函数的语法:


example::~example()
{
	//destructor statements;
}

Here, as you can see, the destructor function(~example()) has the same name as that of the class it belongs to.

如您所见,在这里,析构函数( ~example() )与其所属类的名称相同。

Note: Remember before defining a destructor in C++:

注意:在C ++中定义析构函数之前, 记住:

  • Destructor name and class name must be same

    析构函数名称和类名称必须相同
  • A destructor name should have a tilde(‘~’) before it. For eg. ~example(){}

    析构函数名称前应带有波浪号('〜') 。 例如。 〜example(){}
  • They must not accept any arguments or return anything to the function call

    他们不得接受任何参数或向函数调用返回任何内容
  • A destructor can be virtual

    析构函数可以是虚拟的
  • Derived classes do not inherit the destructor of their base class

    派生类不继承其基类的析构函数
  • There can only one destructor in a single class.

    单个类中只能有一个析构函数。

C ++析构函数示例 (C++ Destructors Example)

Now let us take a look at an example where we try to define our destructor for our demo class.

现在,让我们看一个示例,尝试为演示类定义析构函数。


#include<iostream>
using namespace std;

class demo
{
	public:
		int a=10;
		
		demo() //constructor
		{
			cout<<"Constructor of demo here!"<<endl;
		}
		
		~demo() //destructor
		{
			cout<<"Destructor of demo here!"<<endl;
		}
		
		void print_demo() //function
		{
			cout<<"printed demo"<<endl;
		}
};

int main()
{
	demo demo_obj;  //object of class demo created
	cout<<demo_obj.a<<endl;
	demo_obj.print_demo(); //function called
	return 0;
}  //scope of the object ends

Output:

输出


Constructor of demo here!
10
printed demo
Destructor of demo here!

Here,

这里,

  • Inside the demo class, we have initialized and defined a variable as a=10 and a function print_demo() respectively. Further, we have also defined the corresponding constructor – demo() and destructor – ~demo().

    在演示类内部,我们分别初始化和定义了一个变量a=10和一个函数print_demo() 。 此外,我们还定义了相应的构造函数– demo()和析构函数~demo()
  • Inside the main() function we create an object demo_obj that belongs to the above demo class. This leads to the call for the constructor demo().

    main()函数内部,我们创建一个对象demo_obj ,该对象属于上面的演示类。 这导致对构造函数demo()的调用。
  • Then we also have performed some operations on it like calling the print_demo() function for the object.

    然后,我们还对其执行了一些操作,例如为对象调用print_demo()函数。
  • As soon as the main() function ends, the compiler calls the destructor for the object demo_obj. Which is clear from the above output.

    一旦main()函数结束,编译器便为对象demo_obj调用析构函数。 从上面的输出中可以清楚地看出。

明确调用C ++中的析构函数 (Explicitly Calling Destructors in C++)

Apart from the fact that the compiler calls the default or user-defined destructor as soon as an object gets out of scope. The C++ programming language also allows the user to call the destructor for an object explicitly.

除了一个对象超出范围后,编译器会调用默认或用户定义的析构函数这一事实。 C ++编程语言还允许用户显式调用对象的析构函数

Let us try to call the destructor ~demo() for our previous example code. We just modify our code inside main().

让我们尝试为前面的示例代码调用析构函数~demo() 。 我们只是在main()修改我们的代码。


#include<iostream>
using namespace std;

class demo
{
	public:
		int a=10;
		
		demo() //constructor
		{
			cout<<"Constructor of demo here!"<<endl;
		}
		
		~demo() //destructor
		{
			cout<<"Destructor of demo here!"<<endl;
		}
		
		void print_demo() //function
		{
			cout<<"printed demo"<<endl;
		}
};

int main()
{
    demo obj;
    obj.print_demo();
    obj.~demo();
    return 0;
}

Output:

输出


Constructor of demo here!
printed demo
Destructor of demo here!
Destructor of demo here!

As you can see, as we create an object the constructor demo() is called.

如您所见,在创建对象时,将调用构造函数demo()

After that, we explicitly call the destructor ~demo() for the object obj. This explains the 3rd line of the output ‘Destructor of demo here!’.

之后,我们显式调用对象obj的析构函数~demo() 。 这说明了输出“此处的演示的析构函数!”的第三行

But, the next line is the result of the default calling of the destructor by the compiler at the end of the main() function(since the scope of the object ends).

但是,下一行是编译器在main()函数末尾默认调用析构函数的结果(因为对象范围结束了)。

Note: In case of local variables (the above one) calling the destructor explicitly is not recommended since the destructor will get called again at the close ‘}’ of the block in which the local was created.

注意 :如果是局部变量(上面的一个),则不建议显式调用析构函数,因为析构函数将在创建局部变量的块的结束处“}”处再次调用。

C ++中的虚拟析构函数 (Virtual Destructors in C++)

Destructors in C++ can also be made virtual. They are useful when we try to delete an instance of a derived class through a pointer to base class.

C ++中的析构函数也可以设为虚拟的。 当我们尝试通过指向基类的指针删除派生类的实例时,它们很有用

Now let us look at an example to have a better understanding.

现在让我们看一个例子,以更好地理解。

虚拟析构函数示例 (Virtual Destructor Example)


#include<iostream>
using namespace std;

class Base 
{
	public:
		
		Base()
		{
			cout<<"Base Constructor"<<endl;
		}
 	   virtual ~Base()
		{
			cout<<"Base Destructor"<<endl;
		}
};

class Derived: public Base 
{
	public:
		Derived()
		{
			cout<<"Derived Constructor"<<endl;
		}
		~Derived()
		{
			cout<<"Derived Destructor"<<endl;
		}
};
int main()
{
	Base * b = new Derived;
	delete b;
}

Output:

输出


Base Constructor
Derived Constructor
Derived Destructor
Base Destructor

Notice, this time we have used the virtual keyword before the base destructor.

注意,这一次我们在基本析构函数之前使用了virtual关键字。

It is clear from the output that inside the main() function, the instruction Base *b = new Derived leads to the call for constructors Base() and Derived() respectively.

从输出中很明显,在main()函数内部,指令Base *b = new Derived导致对构造函数 Base()和Derived()的调用。

While deleting the object b, since this time a virtual destructor is inside the base class, hence first the Derived class’s destructor is called and then the Base class’s destructor is called.

自从删除对象b以来,由于这一次虚拟析构函数位于基类内部,因此,首先将调用Derived类的析构函数,然后再调用Base类的析构函数。

Note: if the base class destructor is not virtual then, only the base class object will get deleted(since the pointer is of a base class). This would lead to memory leak for the derived object.

注意 :如果基类析构函数不是虚拟的,则仅基类对象将被删除(因为指针是基类的)。 这将导致派生对象的内存泄漏

为什么要使用析构函数? (Why Destructors?)

Destructors deallocate memory assigned or allocated to different objects in a program as soon as they go out of scope or are explicitly deleted. If it were not for destructors, then the user would have to individually free memory space allocated to different variables or objects. Which is a pretty hectic task.

一旦析构函数超出范围或被显式删除,则析构函数将取消分配或分配给程序中不同对象的内存。 如果不是析构函数,那么用户将必须单独释放分配给不同变量或对象的内存空间。 这是一项非常繁忙的任务。

This automatic de-allocation of memory not only creates a more user-friendly environment to work but also helps manage memory efficiently.

内存的这种自动重新分配不仅创建了更加用户友好的工作环境,而且还有助于有效地管理内存。

结论 (Conclusion)

Thus through this tutorial, we learned about destructors in C++. We also understood the working and use by implementing it in our code.

因此,通过本教程,我们了解了C ++中的析构函数 。 我们还通过在代码中实现它来理解其工作和使用。

For any questions related to this topic, feel free to use the comments below.

对于与该主题相关的任何问题,请随时使用以下评论。

参考资料 (References)

翻译自: https://www.journaldev.com/37885/destructors-in-c-plus-plus

析构函数c+

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值