Boost logo

Boost :

From: Schoenborn, Oliver (Oliver.Schoenborn_at_[hidden])
Date: 2002-10-07 10:03:21

> -----Original Message-----
> From: Daniel Frey [mailto:daniel.frey_at_[hidden]]
> I haven't followed the discussion closely, so please forgive if this has
> been suggested before or if I misunderstood the problem. You want ptr<T>
> to be usable as a ptr< const T >? What about:
> template< typename T > class ptr
> {
> ...
> public:
> operator const ptr< const T >&() const
> {
> return reinterpret_cast< const ptr< const T >& >( *this );
> }
> ...
> };
> Or is reinterpret_cast considered too
> dangerous/non-portable/...? For my
> own pointer-class, this works well (GCC 3.2).

I took a look at the C++ Standard. Paragraph 10 of section 5.2.10 is

"An lvalue expression of type T1 can be cast to the type "reference to T2"
if an expression of type "pointer to T1" can be explicitly converted to the
type "pointer to T2" using a reinterpret_cast. ... The result is an lvalue
that refers to the same object as the source lvalue, but with a different
type. No temporary is created, no copy is made, and constructors (12.1) or
conversion functions (12.3) are not called."

So the reinterpret_cast solution is standard only if there is something in
the Standard that says that the layout for a class<T> MUST be the same as
that for class<const T>, which I don't think is the case (though in practice
it probably ends up like that). Paragraph 10 suggests to me that a
reinterpret cast of the type discussed is not safe when the two classes are
separate, ie is only safe when the cast is within an inheritance branch,
because you can't be sure that the same methods are instantiated in both.
For instance, if you have Base and Derived, then ptr<Derived> may have a
different set of methods instantiate than ptr<Base>, therefore the
reinterpret cast is unsafe.


Boost list run by bdawes at, gregod at, cpdaniel at, john at