I have a C ++ class that contains a non-copyable descriptor. However, the class must have a copy constructor. So, I implemented one that transfers ownership of the descriptor to a new object (as shown below),
class Foo { public: Foo() : h_( INVALID_HANDLE_VALUE ) { }; // transfer the handle to the new instance Foo( const Foo& other ) : h_( other.Detach() ) { }; ~Foo() { if( INVALID_HANDLE_VALUE != h_ ) CloseHandle( h_ ); }; // other interesting functions... private: /// disallow assignment const Foo& operator=( const Foo& ); HANDLE Detach() const { HANDLE h = h_; h_ = INVALID_HANDLE_VALUE; return h; }; /// a non-copyable handle mutable HANDLE h_; }; // class Foo
My problem is that the standard copy constructor accepts a link constant, and I modify that link. So, I would like to know which is better (and why):
Edit:
DuplicateHandle() only works with certain types of descriptors. This is not one of them. This descriptor cannot be duplicated, copied or cloned.
Several people indicated that I was mistaken in suggesting that this is a non-standard copy constructor, and that std::auto_ptr does this. I think that is probably the way to go. But, I get warnings every time I use the class, when I make a copy of ctor, I take a non-constant value. For instance:
namespace detail { class Foo { ... }; }; class Buzz { public: typedef detail::Foo Fuzz; Fuzz bar() const { return Fuzz(); };
Can anyone tell me what I should do with them?
Edit2:
Everyone seems to lead me to the std::auto_ptr<> method of doing things. So, I looked there, and it uses an intermediate structure to get around the problem described in the first edit. This is the solution I came across.
class Foo; struct Foo_ref { explicit Foo_ref( Foo& other ) : ref_( other ) {}; Foo& ref_; private: const Foo_ref& operator=( const Foo_ref& ); };
It automatically compiles at level 4 and seems to work. Please let me know if this will be something more irresponsible than my original post.