【发布时间】:2009-10-14 10:40:25
【问题描述】:
我已阅读有关 DDJ 中范围保护 (Generic: Change the Way You Write Exception-Safe Code — Forever) 的文章,我了解它们的常见用途。
但是,常见的用途是在堆栈上为特定操作实例化特定的堆栈保护,例如:
{
FILE* topSecret = fopen("cia.txt");
ON_BLOCK_EXIT(std::fclose, topSecret);
... use topSecret ...
} // topSecret automagically closed
但是如果我想在运行时安排清理操作怎么办,例如当我有一个循环时:
{
vector<FILE*> topSecretFiles;
for (int i=0; i<numberOfFiles; ++i)
{
char filename[256];
sprintf(filename, "cia%d.txt", i);
FILE* topSecret = fopen(filename);
topSecretFiles.push_back(topSecret);
ON_BLOCK_EXIT(std::fclose, topSecret); // no good
}
}
显然,上面的示例不起作用,因为topSecret 将与 for 范围一起关闭。我想要一个范围保护模式,我可以轻松地将我确定在运行时需要的清理操作排队。有这样的东西吗?
我无法将范围保护对象推送到标准队列中,因为原始对象(我正在推送的对象)将在此过程中被解除。推送堆分配的堆栈保护并使用删除其成员在 dtor 上的队列怎么样?有人有更聪明的方法吗?
【问题讨论】:
标签: c++ design-patterns scopeguard