运算符重载调用析构函数吗
In C++ programming language, there are two operators 1) new and 2) delete, which are used to manage the memory dynamically i.e. to create, delete the memory at run time (dynamically)
在C ++编程语言中,有两个运算符1) new和2) delete ,它们用于动态管理内存,即在运行时(动态)创建,删除内存
Prerequisite: new and delete operators in C++ programming
先决条件: C ++编程中的new和delete运算符
Let’s understand, when 'new' and 'delete' are used?
让我们了解一下, 何时使用“新”和“删除”?
new is used to declare memory blocks at run time (dynamically). While, delete is used to delete/free the memory which has been declared dynamically.
new用于在运行时声明内存块(动态)。 同时, delete用于删除/释放已动态声明的内存。
C ++中的new和delete的示例 (Example of new and delete in C++)
In the given program, we are using new to allocate memory to the class object and delete/free is using to delete the reference of the pointer that will force. There is a class named sample and it has a constructor sample() and a destructor ~sample().
在给定的程序中,我们使用new来为类对象分配内存,而delete / free使用的是删除将强制执行的指针的引用。 有一个名为sample的类,它具有一个构造函数sample()和一个析构函数〜sample() 。
Consider the program:
考虑该程序:
</ s> </ s> </ s>#include <iostream>
using namespace std;
class sample
{
public:
sample()
{
cout<<"Hi ";
}
~sample()
{
cout<<"Bye ";
}
};
int main()
{
sample *obj = new sample();
delete(obj);
return 0;
}
Output
输出量
Hi Bye
You can see, "Hi" is written in the constructor (sample()) while "Bye" is written in the destructor (~sample()).
您会看到, “ Hi”是写在构造函数( sample() )中的,而“ Bye”是写在析构函数( 〜sample() )中的。
Therefore, when object "obj" is creating, constructor will be called and print "Hi", same as when object is going to be freed using delete(obj), destructor (~sample()) will be called and print "Bye".
因此,当创建对象“ obj”时 ,将调用构造函数并显示“ Hi” ,这与将要使用delete(obj)释放对象时相同,将调用析构函数( 〜sample() )并显示“ Bye” 。
运算符重载调用析构函数吗