473,387 Members | 1,495 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

delete does not work

Below is a simple code:

#include <iostream>

class base{
public:
base(): i(11){std::cout<<"base constructor"<<'\n';}
virtual void f() = 0;
virtual ~base(){ std::cout<<"base destructor"<<'\n';}
int i;
};

class derv1 : public base{
public:
derv1(){std::cout<<"derv1 constructor"<<'\n';}
void f(){}
~derv1(){std::cout<<"derv1 destructor"<<'\n';}
};

class derv2 : public derv1{
public:
derv2(){i=22;std::cout<<"derv2 constructor"<<'\n';}
~derv2(){std::cout<<"derv2 destructor"<<'\n';}
};

int main(){
base *b1;
derv1 *d1;

derv2 *d2 = new derv2;

b1 = d2;
std::cout<<b1<<" "<<d2->i<<'\n';
delete b1; //LINE1

std::cout<<"after delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?

Thanks.

Jack

Jun 22 '06 #1
6 2003
* ju******@gmail.com:
int main(){
base *b1;
derv1 *d1;

derv2 *d2 = new derv2;

b1 = d2;
std::cout<<b1<<" "<<d2->i<<'\n';
delete b1; //LINE1

std::cout<<"after delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?


At that point any behavior whatsoever is correct, because the behavior
of accessing the object after destruction, is undefined.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jun 22 '06 #2
junw2000 wrote:
delete b1; //LINE1 std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
Please put spaces around operators, for readability.
I delete b1 at LINE1. Why LINE2 still output the correct result---22?


Because any use of b1 after the delete is undefined behavior. That means the
program could appear to work correctly, or the nearest toilet could explode,
or anything in between.

Tip: Learn all the ways to avoid undefined behavior (basically by avoiding
anything the slightest bit suspicious), and keep all your code within this
subset. For example, many folks use only smart-pointers, and if you can't,
at least do this:

delete b1;
b1 = NULL;

You can test b1 for NULL now, and if you slip up you will _probably_ get a
hard but reliable crash.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Jun 22 '06 #3
Lav

ju******@gmail.com wrote:
Below is a simple code:

#include <iostream>

class base{
public:
base(): i(11){std::cout<<"base constructor"<<'\n';}
virtual void f() = 0;
virtual ~base(){ std::cout<<"base destructor"<<'\n';}
int i;
};

class derv1 : public base{
public:
derv1(){std::cout<<"derv1 constructor"<<'\n';}
void f(){}
~derv1(){std::cout<<"derv1 destructor"<<'\n';}
};

class derv2 : public derv1{
public:
derv2(){i=22;std::cout<<"derv2 constructor"<<'\n';}
~derv2(){std::cout<<"derv2 destructor"<<'\n';}
};

int main(){
base *b1;
derv1 *d1;

derv2 *d2 = new derv2;

b1 = d2;
std::cout<<b1<<" "<<d2->i<<'\n';
delete b1; //LINE1

std::cout<<"after delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?

Thanks.

Jack


Hi Jack,

Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.

Thanks
Lav

Jun 22 '06 #4
Lav wrote:

Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.


You never know how null pointers are going to respond, either. In a code
snippet as short as the original there's no point in setting the pointer
to null. You know from inspection that it shouldn't be used after the
delete. There's no need to test it.

--

Pete Becker
Roundhouse Consulting, Ltd.
Jun 22 '06 #5
Lav wrote:
[snip]
Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.


While this won't *cause* problems (so far as I'm aware)
it won't catch plenty of common newbie problems.

I try to keep pointers as data members of a class.
I also try to keep it such that the pointer is assigned to
memory in an initiation step such as a ctor or a named
ctor, and deleted in the dtor. This way, my memory leaks
and wild pointers are as localized as I can make them,
and tend to be easier to find and easier to correct.

It's an extension of a principle that I illustrate as follows.
Whenever I put a { in code, I immediately put in the
corresponding } to balance it. Then I put in the stuff
that goes between. So too with new calls. Whenever
I put in a new, I immediately put in the delete that
goes with. Then I am careful to only refer to the mem
allocated while between those two. The easy way to
do that is to lean on the object ctor/dtor process.

Similarly with other resources like file streams, etc.
Socks

Jun 22 '06 #6

Puppet_Sock wrote:
Lav wrote:
[snip]
Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.
While this won't *cause* problems (so far as I'm aware)
it won't catch plenty of common newbie problems.


Name one problem that it won't catch that not setting to 0 does.
I try to keep pointers as data members of a class.
I also try to keep it such that the pointer is assigned to
memory in an initiation step such as a ctor or a named
ctor, and deleted in the dtor. This way, my memory leaks
and wild pointers are as localized as I can make them,
and tend to be easier to find and easier to correct.


It is much easier to tell that there is a problem when the pointer has
an obviously erroneous value, like 0, instead of a possibly valid one.
It is hard to figure out that the problem is caused by your object
having been deleted if it looks like a valid object. By setting to 0
you not only increase the likely hood of being able to check if the
pointer has been deleted before calling it, you also increase the
obviousness of the problem when you don't. It is also, though
undefined, much more likely to crash than do something completely
random as read/write to location 0 is always bad and outside your
memory space.

For example. Say you have the following code:

delete x;

When it runs you get an explosion. Why? You look at your ptr and it
has some random value...the object appears normal. Why did it blow up?
You trace back a few miles and end up in some OS specific event loop
and into no-man's land. There is no indication as to why you are
exploding, yet it does. Somewhere, in response to some previous event,
/something/ happened to some object related to that instruction...or
maybe it suffered from a heap thrashing as described below...

What would happen if you had set that value to 0?

Imagine the following code in that scenario:

x->doY(); // doY() writes to a buffer inside an X.

What happens if that pointer was not set to 0? Half the time it
crashes and half the time you get odd heap corruptions and you crash in
totally unrelated areas of code; now you need special debugger tools
and libraries to track buffer overruns and heap corruptions when they
occur and not when their effect is felt...this can take hours, days,
weeks.... What if you had set that to 0? Well, in most systems, you
would crash immediately (except in cases like the OP when the class is
VERY trivial) and the fact that it was because the ptr is invalid would
be very obvious. You could then either fix the logic error that caused
you to do this on a deleted pointer, or if there is no logic problem
and you just need to make sure it never happens:

if (x) x->doY();

There are numerous cases when setting the pointer to 0 saves time by
making bugs more obvious, making intent and purpose clear, and removing
double deletions. There are a few situations in which it doesn't
matter. There is no situation in which it is better not to and there
is no way to track what is happening unless you do.

Jun 22 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that...
11
by: Jonan | last post by:
Hello, For several reasons I want to replace the built-in memory management with some custom built. The mem management itlsef is not subject to my question - it's ok to the point that I have...
5
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space...
3
by: Kevin M | last post by:
I have one table and have created a form from that table. Also, I have created a delete query. I want to but a button on the form which will delete all records from the table; however, I cannot get...
29
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to...
10
by: jeffjohnson_alpha | last post by:
We all know that a new-expression, foo* a = new foo() ; allocates memory for a single foo then calls foo::foo(). And we know that void* p = ::operator new(sizeof(foo)) ; allocates a...
15
by: LuB | last post by:
I am constantly creating and destroying a singular object used within a class I wrote. To save a bit of time, I am considering using 'placement new'. I guess we could also debate this decision -...
12
by: Premal | last post by:
Hi, I tried to make delete operator private for my class. Strangely it is giving me error if I compile that code in VC++.NET. But it compiles successfully on VC++6.o. Can anybody give me inputs...
23
by: Martin T. | last post by:
Hi all! char* p = new char; // POD! .... delete p; // std compliant delete p; // will work on VC8 free(p); // will also work on VC8 I am interested on which platforms/compilers the...
19
by: Daniel Pitts | last post by:
I have std::vector<Base *bases; I'd like to do something like: std::for_each(bases.begin(), bases.end(), operator delete); Is it possible without writing an adapter? Is there a better way? Is...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.