我有一个Visual Studio 2008 C++应用程序,我正在实现替换容器中使用的标准分配器,如std::vector
。但是,我遇到了一个问题。我的实现依赖于拥有资源句柄的分配器。在使用rebind
功能的情况下,我需要将句柄的所有权转移给新的分配器。事情是这样的:在std :: allocator上传递对象的所有权rebind
template< class T >
class MyAllocator
{
public:
template< class U >
explicit MyAllocator(const MyAllocator<U>& other) throw()
: h_(other.Detach()) // can't do this to a `const`
{
};
// ...
private:
HANDLE Detach()
{
HANDLE h = h_;
h_ = NULL;
return h;
};
HANDLE h_;
}; // class MyAllocator
不幸的是,我不能,因为它是const
缓解手柄所有权的老分配器。如果我从rebind构造函数中删除const
,那么容器将不会接受它。
error C2558: class 'MyAllocator<T>' : no copy constructor available or copy constructor is declared 'explicit'
是否有解决此问题的好方法?
感谢,
PaulH
不需要分配器不需要状态?关于分配器的经典文章,Matt Austern,IIRC,但我现在找不到它... – sbi 2011-05-09 19:32:54
这里是文章:[http://drdobbs.com/cpp/184403759](http://drdobbs。 COM/CPP/184403759)。从快速浏览[this discussion](http://gcc.gnu.org/ml/libstdc++/2004-10/msg00303.html),似乎确实支持有状态分配器,尽管std lib实现支持用于成为一个问题。 – sbi 2011-05-09 19:36:10
@sbi - 感谢您的文章和讨论。我打算跟进一个关于如何处理'std :: swap'的问题。 – PaulH 2011-05-09 19:44:03