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=(co nst 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: _CrtIsValidHeap Pointer(pUserDa ta)
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 9 1513
Gutek wrote: B& B::operator=(co nst 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=(co nst 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)
Pete Becker napisał(a):
B& B::operator=(co nst 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=(co nst 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
Gutek wrote: Pete Becker napisał(a):
B& B::operator=(co nst 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=(co nst 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
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
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=(co nst 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)
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)
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=(co nst A& a)
{
delete [] p;
p = new double[a.size];
size = a.size;
copy(a.p, a.p+size,p);
return *this;
}
B& B::operator=(co nst 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
"Gutek" <beztego_g_iteg o_utkowski@vp_i tego.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
Gutek wrote: You mean:
A& A::operator=(co nst A& a) { delete [] p; p = new double[a.size]; size = a.size; copy(a.p, a.p+size,p); return *this; }
B& B::operator=(co nst 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) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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" is called in Case 2 since only ~base() becomes
"virtual" and ~Derived() is still non-virtual?
3. Does Case 3 show that we don't need any virtual destructor to make
~Derived() called?
4. Is "virtual destructor" needed only for Case 2?
|
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
destructors.
What I am expecting is, if the destructor is declared as virtual in
base, the destructors of all its derived classes also should be
virtual always.
What exactly is the reason for not having it so?
|
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 the case when the class contains at
least one virtual member function? Shouldn't the destructor always be
virtual, whenever there's a possibility that an inherited object will
be destructed through a base class pointer? (This does not require,
|
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 ]
|
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 add a virtual destructor like this :
" virtual ~vechile". I get this error:
Undefined first referenced
symbol in file
vtable for vechile /var/tmp//ccC9yD6Z.o
| |
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 to pass all the necessary object files to the linker.
Neither of those are my problem. Please bear with me as the question
I ask is rather long and I think it's beyond a CS101 level of linker
stupidity. If it is a stupid CS101 mistake I'm making...
|
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 item 7 for why this is virtual
...
|
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 virtual destructor whats the use of it?
the code is like this:
Network(int input,int output);
Network(&Network);
virtual ~Network();
|
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;" instead? I think declaring a function as "=0" is the same
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |