C++ - "Stack automatic"是什么意思?

标签 c++ oop

在我浏览互联网时,我遇到了this post , 其中包括这个

"(Well written) C++ goes to great lengths to make stack automatic objects work "just like" primitives, as reflected in Stroustrup's advice to "do as the ints do". This requires a much greater adherence to the principles of Object Oriented development: your class isn't right until it "works like" an int, following the "Rule of Three" that guarantees it can (just like an int) be created, copied, and correctly destroyed as a stack automatic."

我已经完成了一些 C 和 C++ 代码,但只是顺便说一句,从来没有任何严肃的事情,但我很好奇,它到底意味着什么?

有人能举个例子吗?

最佳答案

堆栈对象由编译器自动处理。

当作用域离开时,它被删除。

{
   obj a;
} // a is destroyed here

当您对"new"对象执行相同操作时,您会发生内存泄漏:

{
    obj* b = new obj;
}

b 没有被销毁,所以我们失去了回收 b 拥有的内存的能力。更糟糕的是,该对象无法自行清理。

在 C 中,以下是常见的:

{
   FILE* pF = fopen( ... );
   // ... do sth with pF
   fclose( pF );
}

在 C++ 中我们这样写:

{
   std::fstream f( ... );
   // do sth with f
} // here f gets auto magically destroyed and the destructor frees the file

当我们忘记在 C 示例中调用 fclose 时,文件不会关闭并且可能不会被其他程序使用。 (例如不能删除)。

另一个例子,演示对象字符串,它可以被构造、赋值并在退出作用域时被销毁。

{
   string v( "bob" );
   string k;

   v = k
   // v now contains "bob"
} // v + k are destroyed here, and any memory used by v + k is freed

关于C++ - "Stack automatic"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30099/

相关文章:

c++ - 如何计算预期的核心文件大小

c++字符串文字并置连接

c++ - 类未定义

c++ - 将对象从派生对象转换为基础对象,然后再返回

c++ - 如何在 C++ 程序中更新时间?

javascript - 为什么在对象内部调用函数时 "this.myFunction"不起作用?

c++ - 通过继承层次结构进行 dynamic_casting 是不好的做法吗?

表示性别或性别的 Ruby 约定

php - 意外的 T_VARIABLE,期待 T_FUNCTION 修复

c - 卢阿 :new from C API