C ++ - 析构函数 [英] C++ - destructors

查看:190
本文介绍了C ++ - 析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在阅读的外部C ++学习资源中。



这个语句的例子是什么?



当变量超出范围,或使用delete关键字显式删除动态分配的变量时,将调用类析构函数(如果存在),以帮助在从内存中删除类之前清理类。



而且,动态分配的内存是什么意思?

$


p>当变量超出范围




  void foo()
{
MyClass C;
C.callSomeMethod();
} // C在这里超出范围




或动态分配的变量是
使用delete
关键字显式删除




  void foo()
{
MyClass * C = new MyClass; //在堆上分配
delete C; // deleted assigned memory
...
}


In the external C++ learning resource that I'm reading.

What is an example on this statement?

When a variable goes out of scope, or a dynamically allocated variable is explicitly deleted using the delete keyword, the class destructor is called (if it exists) to help clean up the class before it is removed from memory.

And, what do we mean by dynamically allocated memory?

Thanks.

解决方案

Examples

When a variable goes out of scope

void foo()
{
   MyClass C;
   C.callSomeMethod();
}  // C is here going out of scope

or a dynamically allocated variable is explicitly deleted using the delete keyword

void foo()
{
  MyClass* C = new MyClass; // allocating on heap
  delete C; // deleting allocated memory
...
}

这篇关于C ++ - 析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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