【发布时间】:2015-08-01 18:45:59
【问题描述】:
我有一些 Java 方面的背景(最近在 C# 方面),也想更好地了解 C++。我想我知道这些语言之间内存(和其他资源)管理差异的一些基础知识。这可能是一个与使用dispose pattern 以及这些语言中可用的不同功能来协助它相关的小问题。我喜欢我收集的 RAII and SBRM 原则,我正在努力进一步理解它们。
假设我在 Java 中有以下类和方法
class Resource implements Closeable {
public void close() throws IOException {
//deal with any unmanaged resources
}
}
...
void useSomeResources() {
try(Resource resource = new Resource()) {
//use the resource
}
//do other things. Resource should have been cleaned up.
}
或相当接近的 C# 类似物
class Resource : IDisposable
{
public void Dispose()
{
//deal with any unmanaged resources
}
}
...
void UseSomeResources()
{
using(var resource = new Resource())
{
//use the resource
}
//do other things. Resource should have been cleaned up.
}
我认为在 C++ 中最能代表这种相同行为的成语如下是正确的吗?
class Resource {
~Resource() {
cleanup();
}
public:
void cleanup() {
//deal with any non-memory resources
}
};
...
void useSomeResources()
{
{
Resource resource;
//use the resource
}
//do other things. Stack allocated resource
//should have been cleaned up by stack unwinding
//on leaving the inner scope.
}
我特别不想引发关于谁的语言更好之类的争论,但我想知道这些实现可以在多大程度上进行比较,以及它们对于块使用的情况有多健壮资源遇到特殊情况。我可能完全错过了某些事情的重点,而且我永远不太确定处置的最佳实践——为了争论,也许值得假设这里的所有处置/销毁函数都是幂等的——而且这些问题的真正好技巧可能也与这个问题有关。
感谢您的任何指点。
【问题讨论】:
-
是的,这是模式的等价物,因为
resource将在其封闭范围的末尾被销毁。 -
不,这不是模式的等价物。