transferring ownership of an object to std :: allocator rebind

I have a Visual Studio 2008 C ++ application in which I am replacing the standard dispenser used in containers such as std::vector. But I ran into a problem. My implementation relies on a allocator that owns a resource descriptor. In the case where the rebindfunction rebind, I will need to transfer the ownership of the descriptor to the new allocator. Something like that:

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

Unfortunately, I can’t remove the old handle ownership dispenser because it is const. If I remove constrebind from the constructor, the containers will not accept it.

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

Is there a good way around this problem?

+3
source share
4

, h_ mutable?

+1

( ): ctor const ref, other, . , (std::auto_ptr), .
h_ mutable Detach() a const, , , .

+2

, . , , / /. , , , "" . , .

, , , , , , . , ?

+1

, , .

. -. - :

class SharedHandle {
    HANDLE h_;
    int count;
    SharedHandle(HANDLE h) : h_(h), count(1) {}
    ~SharedHandle() { CloseHandle(h_); } // or whatever to release the resource.
    SharedHandle *Ref() { ++count; return this; }
    void Unref() { if(!--count) delete this; }
}

:

explicit MyAllocator( const MyAllocator< U >& other ) throw() 
:  h_( other.h_->Ref() )

, , , hash_map/unordered_map, Microsoft, , . Windows, , - STL.

+1

All Articles