Re: const-correctness loopholes
Il 16/04/2011 12.21, Kai-Uwe Bux ha scritto:
noir wrote:
Unfortunately, this makes copying impossible for all objects, const or not:
template< typename T>
class const_correct_ptr {
typedef T* pointer;
typedef T& reference;
typedef T const * const_pointer;
typedef T const& const_reference;
pointer the_ptr;
const_pointer getThePointer() const { return the_ptr; }
pointer getThePointer() { return the_ptr; }
public:
const_correct_ptr ( const_correct_ptr const& other )
: the_ptr( other.getThePointer() )
{}
const_correct_ptr ( pointer ptr = 0 )
: the_ptr ( ptr )
{}
pointer operator-> ( void ) {
return ( the_ptr );
}
const_pointer operator-> ( void ) const {
return ( the_ptr );
}
reference operator* ( void ) {
return ( *the_ptr );
}
const_reference operator* ( void ) const {
return ( *the_ptr );
}
};
typedef const_correct_ptr< int> int_ptr;
int main ( void ) {
{
int_ptr p1 ( new int ( 5 ) );
int_ptr p2 ( p1 ); // fails to compile
int_ptr const p3 ( p1 ); // fails to compile
}
{
int_ptr const p1 ( new int ( 5 ) );
int_ptr const p2 ( p1 ); // fails to compile
int_ptr p3 ( p1 ); // this is the only line that _should_
// not compile.
}
}
Equivalently, you could just declare the copy-constructor of
const_correct_ptr<> private.
Of course, is also means that any class containing a const_correct_ptr<>
member is not copy-constructible. Often, this is not acceptable.
I see. I can pass some of your tests using a copy constructor that takes
a non-const reference
const_correct_ptr ( const_correct_ptr& other )
: the_ptr( other.getThePointer() )
{}
but then it fails to:
int_ptr const p1 ( new int ( 5 ) );
int_ptr const p2 ( p1 ); // fails to compile
Anyway, this is starting to look too much like a std::auto_ptr
implementation, and my head still hurts from the last time I studied it :)
Thanks,
noir