|
Boost Users : |
From: Kirit Sælensminde (kirit.saelensminde_at_[hidden])
Date: 2007-07-13 05:33:39
Edd Dawson wrote:
> Hi again, Kirit!
>
> Kirit Sælensminde wrote:
>
>> That should force a string constructor only at the end of the chain, the
>> rest of the time passing a pointer.
>
> Based on your suggestion I've come up with a nice and simple solution. Rather
> than doing a single copy at the end I can do once at the beginning, using this
> crazy looking contraption:
>
> template<typename T>
> class ref_once_copied
> {
> public:
> ref_once_copied(const T &obj) : obj_(new T(obj)), referenced_(false) { }
> ~ref_once_copied() { if (referenced_) delete obj_; }
> operator T &() { referenced_ = true; return *obj_; }
>
> private:
> T *obj_;
> bool referenced_;
> };
That looks like a pretty smart move. The first question I had was about
using types so as to eliminate the bool. I.e. arrange for it to return a
slightly different type, maybe via a function used to wrap this class.
Now that I'm looking at it again though I'm not sure that I completely
understand your implementation. It looks to me like you're always
forcing a copy (in the constructor) so what job does referenced_ do? I
can see that it has value if you move the copy from the constructor into
the type cast (the operator T &()), but as it is in the constructor if
the reference isn't taken for some reason then it will leak a T.
It looks like you've changed your mind about the semantics half way
through implementing it.
> I started out using a boost::shared_ptr<> for the obj_ member, but I realised
> that approach outlined above would work just as well and also avoid the extra
> overhead that the reference counting entails.
I agree with this. In a multi-threaded environment those interlocked
increments and decrements aren't cheap. A policy based implementation
might be nice where we can provide the right threading semantics to the
shared_ptr would be cool.
> So I just wanted to say thanks! I wouldn't have gone down this road if it wasn't
> for your suggestion. Perhaps you'll find a use for this in your implementation?
I certainly will! :-)
You're the same Edd that has a C++ JPEG library as well aren't you? I've
bookmarked it and will have a play with that once I get a chance.
K
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net