gpt4 book ai didi

c++ - 资源容器的包装器

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:53:33 24 4
gpt4 key购买 nike

我经常发现自己在本地使用原始指针或其他资源的容器,其中资源是动态分配的。为确保在出现异常或某些其他返回条件时资源不会泄漏,我为容器使用了一个简单的包装器,该包装器具有释放资源的析构函数。为了将其概括为一个有用的实用程序,我想出了这个结构(请忽略模板模板参数的问题,这不是这里的重点):

template<typename Resource, 
template <typename ELEM,
typename ALLOC=std::allocator<ELEM>>
class Container=std::vector>
struct ResourceContainer {
Container<Resource*> resources;
~ResourceContainer() {
std::for_each(resources.begin(), resources.end(), [](Resource* resource) {
delete resource; // more generally, use a template functor to free the resource
});
}
};

示例用法:

class Bar;
void foo() {
ResourceContainer<Bar> bars;
for (int i=0; i<10; ++i) {
bars.resources.push_back(new Bar());
}
}

问题是,作为一个通用实用程序,我不得不开始担心这个结构的范围,并防止用户复制它、返回它等等……总的来说,我希望它表现得像 boost: :scoped_ptr。有谁知道现有的解决方案吗?我可以做一个简单的修改来防止可用性错误吗?

我不能使用智能指针 vector ,因为我有不属于我的遗留代码,它需要一个原始指针容器。

最佳答案

听起来像 Boost Pointer Container Library正是您所需要的。来自动机部分:

Whenever a programmer wants to have a container of pointers to heap-allocated objects, there is usually only one exception-safe way: to make a container of smart pointers like boost::shared_ptr This approach is suboptimal if

  1. the stored objects are not shared, but owned exclusively, or

  2. the overhead implied by smart pointers is inappropriate

This library therefore provides standard-like containers that are for storing heap-allocated or cloned objects (or in case of a map, the mapped object must be a heap-allocated or cloned object). For each of the standard containers there is a pointer container equivalent that takes ownership of the objects in an exception safe manner.

关于c++ - 资源容器的包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13172991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com