Boost logo

Boost :

From: David B. Held (dheld_at_[hidden])
Date: 2002-10-03 16:41:00


"Schoenborn, Oliver" <Oliver.Schoenborn_at_[hidden]> wrote in message
news:35C5DD9F60FED21192B00004ACA6E6C70151C87F_at_nrclonex1.imti.nrc.ca...
> [...]
> I would also like to find out. In any case, I have used this technique to
> get around it:
> [...]

Oddly enough, gcc gives a more informative message:

warning: conversion to a base class will never use a type conversion
operator.

I guess that pretty much explains things, and I guess I can understand
why. I guess that means that if you want implicit conversion, you need
public inheritance. That doesn't seem so bad to me, but maybe others
disagree.

> [...]
> - it prevents the user from passing a non-const smart_ptr<const T>
> (would be dangerous if allowed)

Well, the conversion operator would be nice here, since we could
force it to return a ptr<T const> const, if it would let us. But simply
exposing the base class does present a bit of a problem. However,
in the usage I imagine, it does not:

template <typename T>
class ptr;

template <typename T>
class ptr<T const>
{
public:
  ptr() { }
  T const* operator->() const { return p_; }
private:
  ptr(ptr const&);
  T* p_;
};

template <typename T>
class ptr : public ptr<T const>
{
public:
  ptr() { }

  T* operator->() const { return p_; }
private:
  ptr(ptr const&);
};

class foo
{
public:
    void bar();
};

void baz(ptr<foo const> const& p)
{
    p->bar(); // Caught!
}

int main()
{
    ptr<foo> p;
    baz(p);
}

Note to Eric: go ahead and compile this sample. Note that I have made
ptr<> non-copyable, to demonstrate that the copy c'tor is not called.

It's true that you could accidentally declare:

void baz(ptr<foo const>& p)
{
    p->bar(); // Caught!
}

and thereby modify p. However, this is true in general, and I don't think
it presents a significant risk. This is an interesting idiom, and I would
like to hear other people's comments on it. Not worth the complexity?
Hidden problems/risks?

Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk