C++ - 析构函数

发布于 2024-10-13 07:54:31 字数 189 浏览 6 评论 0原文

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

该声明的示例是什么?

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

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

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

無處可尋 2024-10-20 07:54:31

您最喜欢的 C++ 教程 对此进行了解释第 6.9 节

It's explained in your favorite C++ tutorial in section 6.9.

与往事干杯 2024-10-20 07:54:31

示例

当变量超出范围时

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

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

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

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
...
}
窝囊感情。 2024-10-20 07:54:31

“动态分配的内存”是指通过 new 或 new [] 运算符在动态内存(通常是堆)上分配。

"dynamically allocated memory" means allocated via the new or new [] operator on the dynamical memory (usually the heap).

我们只是彼此的过ke 2024-10-20 07:54:31

动态分配的内存是您自己分配的内存(calloc\malloc\new 等)。如果您(动态)分配内存 - 您还负责释放(免费)

例如,
整数我; -->编译器分配内存(静态)

char *c;
c = malloc(8*sizeof(char)); (动态)

在 C++ 中,当您想要释放对象的内存(销毁对象)时,您可以实现一个在对象被销毁之前调用的例程(自由例程)。它可能很有用(例如,为了释放一些资源,例如关闭文件)

dynamically allocated memory is a memory you allocate by yourself (calloc\malloc\new etc.). if you allocate memory (dynamiclly) - you're also responsible for releasing in (free)

for example,
int i; --> the compiller allocate the memory (static)

char *c;
c = malloc (8*sizeof(char)); (dynamic)

in C++ when you want to release the memory of the object (destroy the object) you can implement a routine that will be called before the object will be destroyed (free routine). it can be useful (for example, in order to release some resources like closing files)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文