我有一个Visual Studio 2008 C++应用程序,我正在实现替换容器中使用的标准分配器(如std::vector
)的功能。但是,我遇到了一个问题。我的实现依赖于分配器拥有资源句柄的所有权。在使用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
。如果我从重新绑定构造函数中删除const
,那么容器将不会接受它。
error C2558: class 'MyAllocator<T>' : no copy constructor available or copy constructor is declared 'explicit'
有没有好的方法解决这个问题?
std::swap
的后续问题。 - PaulH