Fair enough, but I'm not doing this as part of a library. In fact, the
equivalent to B in my case exists for as long as it takes to decide which
one of two R's is going to be deleted. The B goes away shortly after one of
the R's does. B is representative of a system state, not so much a block of
data. In fact, other parts of the system alter their behaviors when B exists
and there is never more than one B at a time.
I suppose it's possible to isolate B by passing its constructor an object
that describes the post-B action to take. That would also require that
something outside of B itself could be alerted to B's destruction (not
currently the case; B invokes delete on itself because it is the only one
that knows when its decision is made). I tried a little too hard to simplify
my example.
- Jeff.
"Peter Koch Larsen" <> wrote in message
news: om...
> "Jeff Rosenfeld" <> wrote in message
news:<>...
> > Hi. Is there anything to be wary of when delete-ing the object to which
a
> > reference refers? Other than being certain that the reference won't be
used
> > again? Notwithstanding the contrived example below, is this really a
> > horrible thing to do, to the extent that I should avoid creating the
> > reference in the first place? In my actual code, B::rr is just a
convenience
> > used during the lifetime of B.
> >
> > Thanks,
> > - Jeff.
> >
> > class R;
> > class B {
> > R& rr;
> > public:
> > B(R& r) : rr(r) {};
> > ~B() { delete &rr; do_other_stuff_in_B(this); };
> > };
> >
> > int main(() {
> > R* pr = new R;
> > B b(*pr);
> > }
>
> This is absolutely horrible. For a start, how can you tell if rr was
> allocated using new? Your class has no evidence whatsoever that this
> is so, thus verifying the correctness of B requires you to examine
> every usage of it.
> Even so, using a reference makes no sense at all. A reference does not
> convey any hint that the refered to object could possibly be allocated
> using new.
>
> The solution: Do not delete the object in B but outside. Then you can
> use new whenever you need so and automatic, faster and safer storage
> in situations where this is feasible - such as main above.
>
> Kind regards
> Peter
|