C++ 中的向量析构函数
本文讨论了析构函数及其在 C++ 中创建向量和字符串时的用途。
C++ 中的析构函数
在 OOP 范例中,析构函数是与每个类相关联的成员函数,只要类的对象被删除或其生命周期结束,它就会自动执行。 此外,为在堆内存上创建的所有变量调用析构函数。
删除此类变量时,将调用析构函数,以便释放内存供以后使用。
析构函数的创建名称与类名称相同,并带有平铺符号前缀 (~
)。 在一个类中,使用构造函数创建的每个对象都通过使用析构函数删除,但顺序与创建顺序相反。
析构函数的语法是:
~ <className>()
{
//coding
}
让我们考虑一个示例类。
#include<iostream>
using namespace std;
class DestructorExample
{
public:
DestructorExample(){
cout<<"In Constructor of DestructorExample"<<endl;
}
~DestructorExample(){
cout<<"In Destructor of DestructorExample";
}
};
int main(){
DestructorExample t;
return 0;
}
这将给出以下输出。
In Constructor of DestructorExample
In Destructor of DestructorExample
C++ 中向量和字符串的析构函数
如果您使用 std::vector
和 std::string
,则当它们的对象超出范围时会自动调用析构函数。 这些类实现了析构函数,当需要删除相应的对象时会自动触发析构函数。
所以你不需要显式地调用它们或实现它们。
但是如果你有一个指向某个类的指针向量,那么这些对象需要像这样显式删除:
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
public:
MyClass()
{
cout << "Object Created" << endl;
}
~MyClass()
{
cout << "Object Destroyed" << endl;
}
};
int main()
{
vector<MyClass*> testVec;
// Creating the objects
MyClass* p = NULL;
for (int i = 0; i < 3; i++)
{
p = new MyClass();
testVec.push_back(p);
}
// Destroying the objects
for (auto p: testVec)
{
delete p;
}
testVec.clear();
return 0;
}
输出结果如下:
Object Created
Object Created
Object Created
Object Destroyed
Object Destroyed
Object Destroyed
我们遍历向量并显式删除每个对象。 堆中的内存已被释放; 因此,我们可以使用 .clear()
方法删除向量的所有元素。
现在应该明确删除 MyClass*
对象; vector 不会删除这些对象。 因此,你可以说,如果向量中有简单的类对象,这些对象将被自动删除。
但是,如果您有一个指针,则必须明确删除它。
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。