which is better: a lying copy constructor or a non-standard one?

Posted by PaulH on Stack Overflow See other posts from Stack Overflow or by PaulH
Published on 2010-06-09T15:38:51Z Indexed on 2010/06/09 15:42 UTC
Read the original article Hit count: 186

Filed under:

I have a C++ class that contains a non-copyable handle. The class, however, must have a copy constructor. So, I've implemented one that transfers ownership of the handle to the new object (as 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 takes a const-reference and I'm modifying that reference. So, I'd like to know which is better (and why):

  1. a non-standard copy constructor: Foo( Foo& other );

  2. a copy-constructor that 'lies': Foo( const Foo& other );

Thanks, PaulH

© Stack Overflow or respective owner

Related posts about c++