gpt4 book ai didi

c++ - 在 std::allocator 重新绑定(bind)时转移对象所有权

转载 作者:太空狗 更新时间:2023-10-29 20:47:21 25 4
gpt4 key购买 nike

我有一个 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。如果我从重新绑定(bind)构造函数中删除 const,那么容器将不会接受它。

error C2558: class 'MyAllocator<T>' : no copy constructor available or copy constructor is declared 'explicit'

有解决这个问题的好方法吗?

最佳答案

在不太了解分配器的情况下(从不需要它们):您的复制构造函数采用 const ref,因此 promise 不会更改 other 对象,但您尝试无论如何都要改变它。尽管在某些情况下类是以这种方式设计的(std::auto_ptr),但这看起来确实有问题。
从句法上讲,您总是可以声明 h_ mutable,并使 Detach() 成为 const 成员函数,但我'在使用大刀闯过句法丛林之前,我会认真质疑此设置的语义

关于c++ - 在 std::allocator 重新绑定(bind)时转移对象所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5940986/

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