Topic: Doubt on dynamic_cast


Author: comeau@panix.com (Greg Comeau)
Date: 1999/05/23
Raw View
In article <nzwvym30x4.fsf@volumnia.robots> Andrew Fitzgibbon <awf@robots.ox.ac.uk> writes:
AF>David R Tribble <dtribble@technologist.com> writes:
AF>>Arunvijay Kumar wrote:
AF>>> I would like to know if there is any standard method in C++ to find
AF>>> out if an object pointed to by a pointer has been destructed (a
AF>>> delete has been called on some other pointer which points to the same
AF>>> object).
AF>
AF>>Nope.  The only guaranteed way to check that a pointer doesn't point
AF>>to something is to compare it to null.
AF>
AF>>Which means that if you didn't set the pointer to null after you
AF>>deleted its object, you've got problems.  That's why I always set it
AF>>explicitly after every delete:
AF>
AF>>    delete p, p = NULL;
AF>
AF>To paraphrase what I say to young engineers ("Just because it's
AF>counterintuitive doesn't mean it's right"):
AF>
AF>Just because it looks silly doesn't mean it's good practice.
AF>
AF>I don't mean to be that rude really, but so many of these rules make code
AF>more difficult to read.
AF>
AF>I look at that code and say "Oh, that's odd, someone's going to check p for
AF>nullity later."  I then commit that factoid to memory while reading the
AF>rest of the function, in case it turns out to be handy, only to find that
AF>it wasn't.  Cos I can only remember seven things at once, that extra detail
AF>could bust my mental cache, meaning that I misunderstand some other part of
AF>the code, make a wrong change, commit it, ship it, and be responsible for
AF>the needless loss of millions of lives...

Well, you could have read it improperly as some would do:

    delete (p, p = NULL);

and then you wouldn't need to remember so much :)

- Greg
--
       Comeau Computing, 91-34 120th Street, Richmond Hill, NY, 11418-3214
     Producers of Comeau C/C++ 4.2.38 -- New Release!  We now do Windows too.
    Email: comeau@comeaucomputing.com / Voice:718-945-0009 / Fax:718-441-2310
                *** WEB: http://www.comeaucomputing.com ***
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: "Daniel Parker" <dparker@no_spam.globalserve.net>
Date: 1999/05/13
Raw View
Andrew Fitzgibbon <awf@robots.ox.ac.uk> wrote in message
news:nzwvym30x4.fsf@volumnia.robots...
>
> >Which means that if you didn't set the pointer to null after you
> >deleted its object, you've got problems.  That's why I always set it
> >explicitly after every delete:
>
> >    delete p, p = NULL;
>
> To paraphrase what I say to young engineers ("Just because it's
> counterintuitive doesn't mean it's right"):
>
> I look at that code and say "Oh, that's odd, someone's going to check for
> nullity later."

Not me.  I'd look at that code and say, well, nothing really.  On the other
hand, if in the course of debugging I got an assertion on a null pointer,
I'd be greatful to the original programmer.

--
Regards,
Daniel Parker danielaparker@hotmail.com



[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: fysx <fysx@shaw.wave.ca>
Date: 1999/05/13
Raw View
Daniel Parker wrote:

> Andrew Fitzgibbon <awf@robots.ox.ac.uk> wrote in message
> news:nzwvym30x4.fsf@volumnia.robots...
> >
> > >Which means that if you didn't set the pointer to null after you
> > >deleted its object, you've got problems.  That's why I always set it
> > >explicitly after every delete:
> >
> > >    delete p, p = NULL;
> >
> > To paraphrase what I say to young engineers ("Just because it's
> > counterintuitive doesn't mean it's right"):
> >
> > I look at that code and say "Oh, that's odd, someone's going to check for
> > nullity later."
>
> Not me.  I'd look at that code and say, well, nothing really.  On the other
> hand, if in the course of debugging I got an assertion on a null pointer,
> I'd be greatful to the original programmer.

i use a pointer<> which deletes it's member and sets it's value to null when i
call it's member function release().  i use conditional compiles to generate
code for each operator->() to check for nullity and throw an
assertion::require.  the pointer member is also null upon creation.  no pointer
arithmetic is allowed accept for asignments.  this is basically idiot proof...
the user can still forget to call release() which will cause a memory leak...
but you pay that price using traditional new/delete anyways...  this does not
work with new[]/delete[]... instead i use a static_array<> and dynamic_array<>

there is also *no* overhead for these classes when all assertions are turned
off.

fysx
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Valentin Bonnard <Bonnard.V@wanadoo.fr>
Date: 1999/05/13
Raw View
fysx wrote:

> this is basically idiot proof...

It isn't. The debug version is safe, but we it comes to the
real world, the pointers can get invalid values and it becomes
unsafe... It's very easy to be fooled by this kind of
behaviour^Htraps.

So maybe it's idiot-proof (the idiots always disable the
safeties, and aren't beaten by them), but it isn't
good-programmer-proof (the good programmer uses the safety
``features'' (spelled with 4 letters)).

Or maybe I have misunderstoud what you were trying to do ?

Anyway the right solution is to set the pointer to _an
invalid value_ in the debug version, if it hasn't already
a _sufficiently_ invalid value. (0xDEADBEEF comes to mind.)

--

Valentin Bonnard


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Andrew Fitzgibbon <awf@robots.ox.ac.uk>
Date: 1999/05/06
Raw View

David R Tribble <dtribble@technologist.com> writes:

>Arunvijay Kumar wrote:
>> I would like to know if there is any standard method in C++ to find
>> out if an object pointed to by a pointer has been destructed (a
>> delete has been called on some other pointer which points to the same
>> object).

>Nope.  The only guaranteed way to check that a pointer doesn't point
>to something is to compare it to null.

>Which means that if you didn't set the pointer to null after you
>deleted its object, you've got problems.  That's why I always set it
>explicitly after every delete:

>    delete p, p = NULL;

To paraphrase what I say to young engineers ("Just because it's
counterintuitive doesn't mean it's right"):

Just because it looks silly doesn't mean it's good practice.

I don't mean to be that rude really, but so many of these rules make code
more difficult to read.

I look at that code and say "Oh, that's odd, someone's going to check p for
nullity later."  I then commit that factoid to memory while reading the
rest of the function, in case it turns out to be handy, only to find that
it wasn't.  Cos I can only remember seven things at once, that extra detail
could bust my mental cache, meaning that I misunderstand some other part of
the code, make a wrong change, commit it, ship it, and be responsible for
the needless loss of millions of lives...

--
Dr. Andrew Fitzgibbon,                                    awf@robots.ox.ac.uk
Robotics Research Group, University of Oxford                +44 01865 273127
            <a href=http://www.robots.ox.ac.uk/~awf> Home Page </a>
                         "Never say there is no way"


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: "AllanW {formerly AllanW@my-dejanews.com}" <allan_w@my-dejanews.com>
Date: 1999/04/13
Raw View
Arunvijay Kumar wrote:
> >> I would like to know if there is any standard method in C++ to find
> >> out if an object pointed to by a pointer has been destructed (a
> >> delete has been called on some other pointer which points to the same
> >> object).

David R Tribble <dtribble@technologist.com> writes:
> > Nope.  The only guaranteed way to check that a pointer doesn't point
> > to something is to compare it to null.
> >
> > Which means that if you didn't set the pointer to null after you
> > deleted its object, you've got problems.  That's why I always set it
> > explicitly after every delete:
> >
> >     delete p, p = NULL;

Steve Clamage wrote:
> > And what about copies of that pointer elsewhere in the program?
> > That coding practice leads to a false sense of security: you
> > tend to assume that every non-null pointer is valid.
>

David R Tribble <dtribble@technologist.com> wrote:
> Ensuring that all of the other pointers to the deleted object
> are also set to null goes beyond the problem of setting the one
> pointer to null immediately after its object is deleted.  Perhaps
> I'm getting the wrong impression from your statement, but are
> you advocating leaving the pointer unchanged after a delete?

If he isn't, I am. Forgive me if this isn't 100% on topic. It's
more about techniques than about standards, but the reason for
this is that the standard SEEMS to imply something (setting a
pointer to NULL signifies that it's deleted) when in fact it
does not.

Naturally, there are programs that set up a context where a null
value is meaningful, and I wouldn't advocate changing them. For
instance, consider a hypothetical container Box which contains
either 0 or 1 instances of an object. Surely Box::empty() will
set it's internal pointer to NULL, because if it did not do so,
it would need some other variable to track it's state (full or
empty), which would be pointless (pardon the pun).

But routinely setting a pointer to null simply because the
object it used to point to has now been deleted simply doesn't
solve the problem it allegedly adresses. In some cases, where
code mistakenly deletes the object twice, it can mask the
error by neutering one of the deletes 99% of the time. As you
probably realize, a problem solved 99% of the time is much
worse than a problem solved 0% of the time, because it's much
harder to find.

> Or to counter your statement from another angle: I'm more secure
> about the value of 'p' after its object is deleted by explicitly
> setting it to null than if I hadn't set it to anything at all.
> I at least have no false sense of security about pointer 'p',
> in spite of my possible false sense of security about all of the
> other pointers to the object.
>
> > A better approach is to use an ownership discipline that does
> > not leave dangling pointers.
> >
> > For example, an object doesn't get deleted until anything that
> > can point to it has gone out of scope or othewise been destroyed.
> > Sometimes that means transferring ownership of the pointer.
>
> Well, of course.  But at some point, these other pointers should
> get set to null, right?

I'm not speaking for Steve, but in my opinion this isn't usually the
right tack.

Perhaps sometimes it is correct. At the point in the logic where the
object is deleted, it may be possible to locate every one of the
pointers to the object and set them to null. (Special case for Box,
above, where "every one of the pointers" is presumed to be "the one
and only pointer.") But no in general.

    void bad_foo(Bar *bar) {
        baz(bar); // baz sometimes deletes bar
        // Next line has a logic error!
        if (bar)  // Was it deleted?
            bar->do_something();
    }

    void good_foo(Bar *bar) {
        // We need to call baz(bar), but baz sometimes deletes bar
        // We don't know if this is one of those times,
        // so refrain from using bar after calling baz(bar)!
        bar->do_something();
        baz(bar); // Sometimes deletes bar
    }

> My point is that it's wise to set a pointer
> to null as close to the point of deletion (or point of transfer of
> ownership) as possible, regardless of the values of other pointers.

As in:
    void baz(Bar *b) {
        if (b->ready()) {
            delete b;
            b = NULL; // This statement accomplishes NOTHING!
        }
    }

Here we set the pointer to NULL just before it goes out of scope,
solving nothing at all. Note that it doesn't erase the pointer
used by the caller. Yes, I know we could change baz to take a
reference to a baz*, but this simply knocks the problem up one
level on the heirarchy chart. Eventually this point must hit
home: For every object created with new, either the logic or
some state variable(s) must be used to "know" if object has been
deleted. This *CAN* be the pointer variable, but only in certain
circumstances:
  * if there is only one pointer variable for the object, or
  * if all code using other pointers to this object "know" that
    the object might be deleted, and either
    --> Check for this in some way (i.e. by using some other
        state variable), or
    --> Completely refrain from using the object, just in case.

----
Allan_W@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: David R Tribble <dtribble@technologist.com>
Date: 1999/04/14
Raw View
"AllanW {formerly AllanW@my-dejanews.com}" wrote:
>
> David R Tribble <dtribble@technologist.com> writes:
>>>  The only guaranteed way to check that a pointer doesn't point
>>> to something is to compare it to null.
>>>
>>> Which means that if you didn't set the pointer to null after you
>>> deleted its object, you've got problems.  That's why I always set it
>>> explicitly after every delete:
>>>
>>>     delete p, p = NULL;
>
> Steve Clamage wrote:
>>> And what about copies of that pointer elsewhere in the program?
>>> That coding practice leads to a false sense of security: you
>>> tend to assume that every non-null pointer is valid.
>
> David R Tribble <dtribble@technologist.com> wrote:
>> Ensuring that all of the other pointers to the deleted object
>> are also set to null goes beyond the problem of setting the one
>> pointer to null immediately after its object is deleted.  Perhaps
>> I'm getting the wrong impression from your statement, but are
>> you advocating leaving the pointer unchanged after a delete?
>
> If he isn't, I am. Forgive me if this isn't 100% on topic. It's
> more about techniques than about standards, but the reason for
> this is that the standard SEEMS to imply something (setting a
> pointer to NULL signifies that it's deleted) when in fact it
> does not.
>
>[snip]
>
> But routinely setting a pointer to null simply because the
> object it used to point to has now been deleted simply doesn't
> solve the problem it allegedly adresses.

No, but not setting it to null certainly creates a new problem:
dangling pointers to dead objects.

Or, to reverse the wording from Steve: That coding practice leads
to a false sense of insecurity: you tend to assume that every
non-null pointer is meaningless (and might point to a dead object).
It's also harder to know that a non-null pointer really points to a
live object.

> In some cases, where
> code mistakenly deletes the object twice, it can mask the
> error by neutering one of the deletes 99% of the time. As you
> probably realize, a problem solved 99% of the time is much
> worse than a problem solved 0% of the time, because it's much
> harder to find.

So presumably, then, dangling pointers are an easier kind of bug
to find?

>>[snip]
>> My point is that it's wise to set a pointer
>> to null as close to the point of deletion (or point of transfer of
>> ownership) as possible, regardless of the values of other pointers.
>
> As in:
>     void baz(Bar *b) {
>         if (b->ready()) {
>             delete b;
>             b = NULL; // This statement accomplishes NOTHING!
>         }
>     }
>
> Here we set the pointer to NULL just before it goes out of scope,
> solving nothing at all.

Yes, that's true.  This is a poor design, or a design that requires
some good documentation if a client of baz() is expected to use it
correctly.

But consider managing pointers that are members of other objects:

    void Foo::baz()
    {
        if (this->ready())
        {
            delete this->ptr;
            this->ptr = NULL;   // This accomplishes something!
        }
    }

You're not advocating that, in this case, I should leave this->ptr
a non-NULL value after the delete, are you?

I might not be talking about all pointer instances here, but I am
certainly talking about pointers that are the sole owner of (i.e.,
the sole point of access to) an allocated object.  Once they no
longer have an object to point to, they most certainly must be set
to null.  Otherwise, you're simply creating bugs.

> Eventually this point must hit home:
> For every object created with new, either the logic or
> some state variable(s) must be used to "know" if object has been
> deleted. This *CAN* be the pointer variable, but only in certain
> circumstances:
>   * if there is only one pointer variable for the object, or
>   * if all code using other pointers to this object "know" that
>     the object might be deleted, and either
>     --> Check for this in some way (i.e. by using some other
>         state variable), or
>     --> Completely refrain from using the object, just in case.

Yes.  In these cases (of which my code above is an example of the
first case), my rule holds true.

-- David R. Tribble, dtribble@technologist.com --
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Bruce Visscher <bvisscher@mindspring.com>
Date: 1999/04/15
Raw View
"AllanW {formerly AllanW@my-dejanews.com}" wrote:

> [...]
>
> But routinely setting a pointer to null simply because the
> object it used to point to has now been deleted simply doesn't
> solve the problem it allegedly adresses. In some cases, where
> code mistakenly deletes the object twice, it can mask the
> error by neutering one of the deletes 99% of the time. As you
> probably realize, a problem solved 99% of the time is much
> worse than a problem solved 0% of the time, because it's much
> harder to find.

IMHO, given the current definition of the language, the main problem that
setting a pointer to null solves is exception safety:

class X {
//...
    void f() {
        delete[] p;
        p=0;
        p = new char[aBigNumber];
    }
    char* p;
    ~X() {delete[] p;}
//...
};

Doing this (setting p to 0 after a delete) routinely seems like a good idea
(well, using smart pointers is even better but that's beside the point).  What
am I missing?

Bruce Visscher
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: sirwillard@my-dejanews.com
Date: 1999/04/15
Raw View
In article <7etsft$hqt$1@nnrp1.dejanews.com>,
  "AllanW {formerly AllanW@my-dejanews.com}" <allan_w@my-dejanews.com> wrote:
> Arunvijay Kumar wrote:
> > Ensuring that all of the other pointers to the deleted object
> > are also set to null goes beyond the problem of setting the one
> > pointer to null immediately after its object is deleted.  Perhaps
> > I'm getting the wrong impression from your statement, but are
> > you advocating leaving the pointer unchanged after a delete?
>
> If he isn't, I am. Forgive me if this isn't 100% on topic. It's
> more about techniques than about standards, but the reason for
> this is that the standard SEEMS to imply something (setting a
> pointer to NULL signifies that it's deleted) when in fact it
> does not.

The standard doesn't imply that an object has been deleted when the pointer is
NULL.  It only implies that there's nothing to delete.  This is not the same
thing.

> Naturally, there are programs that set up a context where a null
> value is meaningful, and I wouldn't advocate changing them. For
> instance, consider a hypothetical container Box which contains
> either 0 or 1 instances of an object. Surely Box::empty() will
> set it's internal pointer to NULL, because if it did not do so,
> it would need some other variable to track it's state (full or
> empty), which would be pointless (pardon the pun).
>
> But routinely setting a pointer to null simply because the
> object it used to point to has now been deleted simply doesn't
> solve the problem it allegedly adresses. In some cases, where
> code mistakenly deletes the object twice, it can mask the
> error by neutering one of the deletes 99% of the time. As you
> probably realize, a problem solved 99% of the time is much
> worse than a problem solved 0% of the time, because it's much
> harder to find.

It sure does solve the problem.  That pointer is no longer a dangling
pointer. All that you are pointing out is that it doesn't solve _all_
problems.  Your further analogy about solving only 99% of the cases being
worse is just plain silly.  Maybe that 1% will be harder to find, but that's
better than not fixing any of the problem.  All that you are advocating is to
leave bad code alone, which makes no sense.

> > Well, of course.  But at some point, these other pointers should
> > get set to null, right?
>
> I'm not speaking for Steve, but in my opinion this isn't usually the
> right tack.
>
> Perhaps sometimes it is correct. At the point in the logic where the
> object is deleted, it may be possible to locate every one of the
> pointers to the object and set them to null. (Special case for Box,
> above, where "every one of the pointers" is presumed to be "the one
> and only pointer.")

If you can't identify every pointer that points to the object in question, you
shouldn't be deleting it in the first place.  Doing so is going to cause bugs,
plain and simple.

> But no in general.
>
>     void bad_foo(Bar *bar) {
>         baz(bar); // baz sometimes deletes bar
>         // Next line has a logic error!
>         if (bar)  // Was it deleted?
>             bar->do_something();
>     }
>
>     void good_foo(Bar *bar) {
>         // We need to call baz(bar), but baz sometimes deletes bar
>         // We don't know if this is one of those times,
>         // so refrain from using bar after calling baz(bar)!
>         bar->do_something();
>         baz(bar); // Sometimes deletes bar
>     }

This example is horrendous.  Firstly, baz should be bad_baz.  No function
should ever delete an object only some of the time.  If it absolutely must
(yeah, right) then it had damn well better be VERY well documented and had
better return some indication as to whether or not it did delete the object
(in other words, I think your bad_foo is better than your good_foo).

Let's consider leaving it your way.  After the call to baz you have no idea
if the object was deleted.  Let's say we had 20+ pointers to this object.  We
now have 20+ pointers that are nearly gaurenteed to cause our program to
fault with absolutely no way to correct this issue even if we can identify
the 20+ dangling pointers.  Great way to basically force bugs into your
program.

> > My point is that it's wise to set a pointer
> > to null as close to the point of deletion (or point of transfer of
> > ownership) as possible, regardless of the values of other pointers.
>
> As in:
>     void baz(Bar *b) {
>         if (b->ready()) {
>             delete b;
>             b = NULL; // This statement accomplishes NOTHING!
>         }
>     }
>
> Here we set the pointer to NULL just before it goes out of scope,
> solving nothing at all. Note that it doesn't erase the pointer
> used by the caller. Yes, I know we could change baz to take a
> reference to a baz*, but this simply knocks the problem up one
> level on the heirarchy chart. Eventually this point must hit
> home: For every object created with new, either the logic or
> some state variable(s) must be used to "know" if object has been
> deleted. This *CAN* be the pointer variable, but only in certain
> circumstances:
>   * if there is only one pointer variable for the object, or
>   * if all code using other pointers to this object "know" that
>     the object might be deleted, and either
>     --> Check for this in some way (i.e. by using some other
>         state variable), or
>     --> Completely refrain from using the object, just in case.

Using a third variable to track this seems like a waste of space, time and
effort.  It gives one a false sense of security (I don't have to track what
pointers to this object exist because I can set this flag and be insured that
we won't have dangling pointers) while retaining all the same pitfalls and
requiring the same amount of coding.  I'd rather manage the code in such a way
that one knows there's not going to be dangling pointers, which means I can
safely and easily set any pointers to NULL when the object is deleted.  Such
management means that your baz function would never have been written.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: David R Tribble <dtribble@technologist.com>
Date: 1999/04/10
Raw View
Arunvijay Kumar wrote:
>> I would like to know if there is any standard method in C++ to find
>> out if an object pointed to by a pointer has been destructed (a
>> delete has been called on some other pointer which points to the same
>> object).

David R Tribble <dtribble@technologist.com> writes:
> Nope.  The only guaranteed way to check that a pointer doesn't point
> to something is to compare it to null.
>
> Which means that if you didn't set the pointer to null after you
> deleted its object, you've got problems.  That's why I always set it
> explicitly after every delete:
>
>     delete p, p = NULL;

Steve Clamage wrote:
> And what about copies of that pointer elsewhere in the program?
> That coding practice leads to a false sense of security: you
> tend to assume that every non-null pointer is valid.

Ensuring that all of the other pointers to the deleted object
are also set to null goes beyond the problem of setting the one
pointer to null immediately after its object is deleted.  Perhaps
I'm getting the wrong impression from your statement, but are
you advocating leaving the pointer unchanged after a delete?

Or to counter your statement from another angle: I'm more secure
about the value of 'p' after its object is deleted by explicitly
setting it to null than if I hadn't set it to anything at all.
I at least have no false sense of security about pointer 'p',
in spite of my possible false sense of security about all of the
other pointers to the object.

> A better approach is to use an ownership discipline that does
> not leave dangling pointers.
>
> For example, an object doesn't get deleted until anything that
> can point to it has gone out of scope or othewise been destroyed.
> Sometimes that means transferring ownership of the pointer.

Well, of course.  But at some point, these other pointers should
get set to null, right?  My point is that it's wise to set a pointer
to null as close to the point of deletion (or point of transfer of
ownership) as possible, regardless of the values of other pointers.

-- David R. Tribble, dtribble@technologist.com --
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: David R Tribble <dtribble@technologist.com>
Date: 1999/03/31
Raw View
Arunvijay Kumar wrote:
> I would like to know if there is any standard method in C++ to find
> out if an object pointed to by a pointer has been destructed (a
> delete has been called on some other pointer which points to the same
> object).

Nope.  The only guaranteed way to check that a pointer doesn't point
to something is to compare it to null.

Which means that if you didn't set the pointer to null after you
deleted its object, you've got problems.  That's why I always set it
explicitly after every delete:

    delete p, p = NULL;

It would be nice if operator delete() was passed the address of the
pointer to the object being deleted, so that you could set the
pointer itself to null, but alas, this is not the case.

Note, however, that the standard states that the operand of the
delete expression has an undefined value after the delete operation,
which seems to imply that the compiler could set the pointer to
null if it wanted to, which would be nice.  (I don't know of any
compilers that do this, though.)

-- David R. Tribble, dtribble@technologist.com --

Lowly Pascal does this for you.  Something like:
    #define dispose(p)  delete (p), (p) = NULL
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: clamage@eng.sun.com (Steve Clamage)
Date: 1999/04/01
Raw View
David R Tribble <dtribble@technologist.com> writes:

>Arunvijay Kumar wrote:
>> I would like to know if there is any standard method in C++ to find
>> out if an object pointed to by a pointer has been destructed (a
>> delete has been called on some other pointer which points to the same
>> object).

>Nope.  The only guaranteed way to check that a pointer doesn't point
>to something is to compare it to null.

>Which means that if you didn't set the pointer to null after you
>deleted its object, you've got problems.  That's why I always set it
>explicitly after every delete:

>    delete p, p = NULL;

And what about copies of that pointer elsewhere in the program?
That coding practice leads to a false sense of security: you
tend to assume that every non-null pointer is valid.

A better approach is to use an ownership discipline that does
not leave dangling pointers.

For example, an object doesn't get deleted until anything that
can point to it has gone out of scope or othewise been destroyed.
Sometimes that means transferring ownership of the pointer.

--
Steve Clamage, stephen.clamage@sun.com
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: "AllanW {formerly AllanW@my-dejanews.com}" <allan_w@my-dejanews.com>
Date: 1999/03/26
Raw View
In article <922174172.202636@demdwu29>,
  "Arunvijay Kumar" <arunvijay@mailexcite.com> wrote:
> Hello,
Hi!

> I would like to know if there is any standard method in C++ to find out if
> an object pointed to by a pointer has been destructed ( a delete has been
> called on some other pointer which points to the same object ).
No, you are required to track this information yourself.

[...]
>     A*  pTemp = dynamic_cast< A* > ( p2 );
>     // is pTemp == 0 here because p2 is not a valid pointer to B
This is invalid.

> if (pTemp == 0) is not guaranteed, are there any problems in requiring
> implementations to guarantee it?
Quite a few. The biggest and most obvious problem: Operator new is
allowed (even encouraged!) to re-use memory that was previously
deleted. In fact, most of the time this is considered a practical
requirement; otherwise a loop that allocates memory, uses it, and
then deletes it could not run indefinately. If the address that
pTemp holds happens to have been re-allocated to some other object,
then the run-time system has no way of knowing that the address is
stale.

    void abc() {
       T*t = new T;  // Say this happens to get address 0x1234
       T*t2 = t;
       // ...
       delete t2;    // Address 0x1234 now reclaimed by runtime system
       t2 = new T;   // Suppose runtime system reuses address 0x1234
       // ...
       if (dynamic_cast< T* > ( t2 ))
           std::cout << "Something's wrong -- deleted T is still valid!\n";
    }

I'm sure that others will come up with many more reasons, but this
one is a show stopper all by itself.

> Thank you,
You're welcome!

----
Allan_W@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: "Arunvijay Kumar" <arunvijay@mailexcite.com>
Date: 1999/03/23
Raw View
Hello,

I would like to know if there is any standard method in C++ to find out if
an object pointed to by a pointer has been destructed ( a delete has been
called on some other pointer which points to the same object ).

Specifically,

class A { ... };

class B : public A { ... };

B*  p1, p2;

void main()
{
    p1 = new B;
    p2 = p1;
    delete p1;

    A*  pTemp = dynamic_cast< A* > ( p2 );
    // is pTemp == 0 here because p2 is not a valid pointer to B
}

if (pTemp == 0) is not guaranteed, are there any problems in requiring
implementations to guarantee it?

Thank you,

Arunvijay
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Stephen.Clamage@sun.com (Steve Clamage)
Date: 1999/03/23
Raw View
"Arunvijay Kumar" <arunvijay@mailexcite.com> writes:

>I would like to know if there is any standard method in C++ to find out if
>an object pointed to by a pointer has been destructed ( a delete has been
>called on some other pointer which points to the same object ).

No. You have to keep track of that yourself.

>void main()
>{
>    p1 = new B;
>    p2 = p1;
>    delete p1;

>    A*  pTemp = dynamic_cast< A* > ( p2 );
>    // is pTemp == 0 here because p2 is not a valid pointer to B
>}

The results of using a pointer to a deleted object (even just
reading its value) are undefined. All you can safely do with
such a pointer is assign it a new value.

>if (pTemp == 0) is not guaranteed, are there any problems in requiring
>implementations to guarantee it?

The implementation cannot know which objects you might be
interested in, so it would have to mark or in some way keep
track of everything allocated and deallocated on the heap.
That is a very expensive requirement (in time and space).

Some implementations will keep track of memory and pointers
for you on request, and add-on packages exist which will
do that for a variety of implementations. Try out one of
those schemes, and notice the effect it has on program
size and speed. (The difference is dramatic.)

The C++ standard doesn't require the implementation to keep track
of heap memory and pointers because it would make it impossible
to have standard-conforming efficient programs.

It might be different if C++ didn't allow the promiscuity of
pointers that it inherited from C.

--
Steve Clamage, stephen.clamage@sun.com


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Martin von Loewis <loewis@informatik.hu-berlin.de>
Date: 1999/03/23
Raw View
"Arunvijay Kumar" <arunvijay@mailexcite.com> writes:

> I would like to know if there is any standard method in C++ to find out if
> an object pointed to by a pointer has been destructed ( a delete has been
> called on some other pointer which points to the same object ).

No, there is no such method. Accessing a pointer to an object that has
been destroyed causes undefined behaviour. In particular,
dynamic_casting that pointer gives undefined results.

> if (pTemp == 0) is not guaranteed, are there any problems in requiring
> implementations to guarantee it?

Requiring that would require implementations to keep track of life
objects. This never was a feature of C++, and it would be
implementable only at significant costs.

There are various approaches out there to allow to track pointer usage
(garbage collection, reference counting, other kinds of smart
pointers). Which approach is best depends on your application, and you
can implement a number of them using standard C++.

Regards,
Martin


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1999/03/24
Raw View
In article <922174172.202636@demdwu29>, Arunvijay Kumar
<arunvijay@mailexcite.com> writes
>I would like to know if there is any standard method in C++ to find out if
>an object pointed to by a pointer has been destructed ( a delete has been
>called on some other pointer which points to the same object ).

For plain pointers the answer is no, nor IMO will there ever be.

Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: JHB NIJHOF <nijhojhb@aston.ac.uk>
Date: 1999/03/24
Raw View
Arunvijay Kumar <arunvijay@mailexcite.com> wrote:
: Hello,

: I would like to know if there is any standard method in C++ to find out if
: an object pointed to by a pointer has been destructed ( a delete has been
: called on some other pointer which points to the same object ).

: Specifically,

: class A { ... };

: class B : public A { ... };

: B*  p1, p2;

: void main()
: {
:     p1 = new B;
:     p2 = p1;
:     delete p1;

:     A*  pTemp = dynamic_cast< A* > ( p2 );
:     // is pTemp == 0 here because p2 is not a valid pointer to B
: }

Not even p1 will be zero, so this is asking for trouble. I don't
know what you want to do, but I think you need something like
reference counting.

--
Jeroen Nijhof      J.H.B.Nijhof@aston.ac.uk
Accordion Links    http://www-th.phys.rug.nl/~nijhof/accordions.html
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]