在我浏览互联网时,我遇到了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/