c 中的向量析构函数
本文讨论了析构函数及其在 c 中创建向量和字符串时的用途。
c 中的析构函数
在 oop 范例中,析构函数是与每个类相关联的成员函数,只要类的对象被删除或其生命周期结束,它就会自动执行。 此外,为在堆内存上创建的所有变量调用析构函数。
删除此类变量时,将调用析构函数,以便释放内存供以后使用。
析构函数的创建名称与类名称相同,并带有平铺符号前缀 (~
)。 在一个类中,使用构造函数创建的每个对象都通过使用析构函数删除,但顺序与创建顺序相反。
析构函数的语法是:
~ ()
{
//coding
}
让我们考虑一个示例类。
#include
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
#include
using namespace std;
class myclass
{
public:
myclass()
{
cout << "object created" << endl;
}
~myclass()
{
cout << "object destroyed" << endl;
}
};
int main()
{
vector 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 不会删除这些对象。 因此,你可以说,如果向量中有简单的类对象,这些对象将被自动删除。
但是,如果您有一个指针,则必须明确删除它。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:c
-
可以通过使用复位按钮,softwarereset 库和 adafruit sleepydog 库来复位 arduino。
发布时间:2024/03/13 浏览次数:181 分类:c
-
可以使用简单的方法 toint()函数和 serial.parseint()函数将 char 转换为 int。
发布时间:2024/03/13 浏览次数:151 分类:c
-
可以使用 arduino 中的循环制作计数器。