473,387 Members | 1,779 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.

Strange behavoiur of a virtual destructor

Hello all,

I have run into the following problem with virtual destructor. I have
following classes:

class A
{
public:
double* p;
A(unsigned int s=0) : { p = new double [s]; }
virtual ~A() { delete [] p; }
};

class B : public A
{
public:
unsigned int val;
B(unsigned int v=0) : A(v), val(v) { }
B& operator=(const B& b);
~B() { }
};

B& B::operator=(const B& b)
{
this->~B();
val = b.val;
p = new double[val];
copy(b.p, b.p+val,p);
return *this;
}
Now I create a dynamic array of objects B:

B* bp = new B[4];
B b(7);
bp[0] = b;
delete [] bp;

Now at the last line the following run-time error occurs:

Debug Assertion Failed!:
Expression: _CrtIsValidHeapPointer(pUserData)

I have checked that only virtual destructor ~A() is called. The strange
thing is that when destructor ~A() is not virtual or b is assigned to
some other cell, e.g. bp[1] = b;, the problem disappears.

Do you know what is the reson of this?

Regards,

Gutek
Jul 23 '05 #1
9 1501
Gutek wrote:

B& B::operator=(const B& b)
{
this->~B();
The object has just been destroyed. Anything done to it after this is,
at best, questionable.
val = b.val;
p = new double[val];
copy(b.p, b.p+val,p);
return *this;
}


B& B::operator=(const B& b)
{
if (this != &b)
{
double *tmp = new double[b.val];
delete [] p;
p = tmp;
copy(b.p, b.p + val, p);
val = b.val;
}
return *this;
}

The order of the new and delete is important: if new throws an exception
the assignment operator leaves *this unchanged.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #2
Pete Becker napisał(a):


B& B::operator=(const B& b)
{
if (this != &b)
{
double *tmp = new double[b.val];
delete [] p;
p = tmp;
copy(b.p, b.p + val, p);
val = b.val;
}
return *this;
}

The order of the new and delete is important: if new throws an exception
the assignment operator leaves *this unchanged.


Thanks, this solves this problem. But what if I need to call the
destructor of A anyway? It may do sth more that just 'delete [] p;', for
example sth on private members of A. When writing my own operator=() I
used to call the destructor instead of do the clean up myself, and then
alloate memory and copy. Can I do sth with the following:

B& B::operator=(const B& b)
{
if (this != &b)
{
double *tmp = new double[b.val];
//delete [] p;
this->~B();
p = tmp;
copy(b.p, b.p + val, p);
val = b.val;
}
return *this;
}

Regard,

Gutek
Jul 23 '05 #3
Gutek wrote:
Pete Becker napisał(a):


B& B::operator=(const B& b)
{
if (this != &b)
{
double *tmp = new double[b.val];
delete [] p;
p = tmp;
copy(b.p, b.p + val, p);
val = b.val;
}
return *this;
}

The order of the new and delete is important: if new throws an exception
the assignment operator leaves *this unchanged.

Thanks, this solves this problem. But what if I need to call the
destructor of A anyway?


Then you should ask yourself why you need that. It's usually needed very
rarely if at all. It's easy to do 10 years of C++ programming 8 hours per
day and never ever need to use an explicit destructor call.
It may do sth more that just 'delete [] p;', for example sth on private
members of A.
Why doesn't A have a proper assignment operator then?
BTW: IMHO, assignment operators on polymorphic types are only of limited
use.
When writing my own operator=() I used to call the destructor instead of
do the clean up myself, and then alloate memory and copy. Can I do sth
with the following:

B& B::operator=(const B& b)
{
if (this != &b)
{
double *tmp = new double[b.val];
//delete [] p;
this->~B();
As someone already told you, the object is destroyed here. There is no
object anymore, so you must not assign its members or call any member
functions of it. On some systems, you might get away with it, but it's not
guaranteed to work. it's bad programming practice and it invokes undefined
behavior. It's one of those "don't do this at home" things.
p = tmp;
copy(b.p, b.p + val, p);
val = b.val;
}
return *this;
}

Regard,

Gutek


Jul 23 '05 #4
Rolf Magnus napisał(a):

As someone already told you, the object is destroyed here. There is no
object anymore, so you must not assign its members or call any member
functions of it. On some systems, you might get away with it, but it's not
guaranteed to work. it's bad programming practice and it invokes undefined
behavior. It's one of those "don't do this at home" things.


Ok. Thank you Pete and Rolf. In fact, this was not my invention to do
so, but I've read somewhere, that destructors do the clean-up but do not
destroy the object, in similar way like constructors initialize the
object but do not create it. Seems that I was misleaded.

Kind regards,

Gutek
Jul 23 '05 #5
Gutek wrote:

Thanks, this solves this problem. But what if I need to call the
destructor of A anyway? It may do sth more that just 'delete [] p;', for
example sth on private members of A.
Don't call the destructor. Write an assignment operator for A, and call
that. (Yes, I know, you can't do that with this particular version of A;
that's a design flaw in A.) Or add a member function to A that cleans it
up, and call that from A's destructor and call it from B's assignment
operator.
When writing my own operator=() I
used to call the destructor instead of do the clean up myself, and then
alloate memory and copy. Can I do sth with the following:

B& B::operator=(const B& b)
{
if (this != &b)
{
double *tmp = new double[b.val];
//delete [] p;
this->~B();


No. You've destroyed the object. There's nothing sensible you can do
with that object any more, because it does not exist.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #6
Gutek wrote:

Ok. Thank you Pete and Rolf. In fact, this was not my invention to do
so, but I've read somewhere, that destructors do the clean-up but do not
destroy the object, in similar way like constructors initialize the
object but do not create it. Seems that I was misleaded.


Constructors construct and destructors destroy. They don't allocate
memory or free it, which is probably what someone was trying to say.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #7
Pete Becker napisał(a):

Don't call the destructor. Write an assignment operator for A, and call
that. (Yes, I know, you can't do that with this particular version of A;
that's a design flaw in A.)
You mean:

A& A::operator=(const A& a)
{
delete [] p;
p = new double[a.size];
size = a.size;
copy(a.p, a.p+size,p);
return *this;
}

B& B::operator=(const B& b)
{
A::operator=(b);
val = b.val;
return *this;
}

?
No. You've destroyed the object. There's nothing sensible you can do
with that object any more, because it does not exist.


It looks like 'destroy' means something more than 'call the code from
the destructor' but still less that 'free the memory of the object'. So
what it is exactly?

Gutek

Jul 23 '05 #8
"Gutek" <beztego_g_itego_utkowski@vp_itego.pl> wrote in message
news:d4**********@news.onet.pl...

I have just had a look at the code presented. It seems flawed.

(i) Because of A's internal pointer, you should write a copy constructor and
assignment operator to handle all this. Failure to do this will eventually
burn you.

(ii) For B, you don't need to bother writing an assignment operator, you can
strip it out. If A's constructor, copy constructor, assignment operator and
destructor all "work", then the automatic compiler-generated versions for B
will call A's equivalents. B, as a class, unlike A, has nothing that needs
manually handling, therefore you don't need to write an assignment operator.

This is the least amount of work.

Stephen Howe
Jul 23 '05 #9
Gutek wrote:

You mean:

A& A::operator=(const A& a)
{
delete [] p;
p = new double[a.size];
size = a.size;
copy(a.p, a.p+size,p);
return *this;
}

B& B::operator=(const B& b)
{
A::operator=(b);
val = b.val;
return *this;
}

?
Yes. That's the usual way: each class is responsible for its own copy
operation.
No. You've destroyed the object. There's nothing sensible you can do
with that object any more, because it does not exist.

It looks like 'destroy' means something more than 'call the code from
the destructor' but still less that 'free the memory of the object'. So
what it is exactly?


I've been deliberately not saying what it means, because it depends on
various implementation details. So read this, but forget it. <g>
Typically, a class with virtual functions has a vtable that holds
pointers to the virtual functions. So an A object has a pointer to A's
vtable, and a B object has a pointer to B's vtable. When you destroy a B
object the destructor does whatever code you've written, then replaces
the vtable pointer with a pointer to A's vtable, then calls A's
destructor. The result is memory with none of the proper internal
details to act as an A object or as a B object.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #10

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

Similar topics

11
by: Stub | last post by:
Please answer my questions below - thanks! 1. Why "Derived constructor" is called but "Derived destructor" not in Case 1 since object B is new'ed from Derived class? 2. Why "Derived destructor"...
7
by: qazmlp | last post by:
When a member function is declared as virtual in the base class, the derived class versions of it are always treated as virtual. I am just wondering, why the same concept was not used for the...
23
by: heted7 | last post by:
Hi, Most of the books on C++ say something like this: "A virtual destructor should be defined if the class contains at least one virtual member function." My question is: why is it only for...
37
by: WittyGuy | last post by:
Hi, I wonder the necessity of constructor and destructor in a Abstract Class? Is it really needed? ? Wg http://www.gotw.ca/resources/clcm.htm for info about ]
26
by: pmizzi | last post by:
When i compile my program with the -ansi -Wall -pedantic flags, i get this warning: `class vechile' has virtual functions but non-virtual destructor, and the same with my sub-classes. But when i...
5
by: druberego | last post by:
I read google and tried to find the solution myself. YES I do know that you can get undefined references if you: a) forget to implement the code for a prototype/header file item, or b) you forget...
7
by: eric | last post by:
hello i'm confused by an example in the book "Effective C++ Third Edition" and would be grateful for some help. here's the code: class Person { public: Person(); virtual ~Person(); // see...
7
by: sam | last post by:
Hi, See when i reading a sourcecode of a program, I read that the constructor is ordinary and after that the programmer has written virtual destructor for that constructor . Why we use the...
17
by: Jess | last post by:
Hello, If I have a class that has virtual but non-pure declarations, like class A{ virtual void f(); }; Then is A still an abstract class? Do I have to have "virtual void f() = 0;"...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
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...

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.