473,785 Members | 2,308 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unexpected destructor call

Hello
Below you will find the problematic program. It is a string wrapper
class with a bare minimum of functionality to keep things simple.

**Code**

//StringClass.h

#include <iostream>
#include <cstring>

using namespace std;

class StringClass{
char* s;
int size;

public:
char* name;
StringClass();
StringClass(cha r* string);

~StringClass();

StringClass operator=(Strin gClass &string);
friend ostream &operator<<(ost ream &output, StringClass &string);
};

StringClass::St ringClass(){
s = new char[0];
size = 0;
}

StringClass::St ringClass(char* string){
size = strlen(string);
s = new char[size + 1];
strcpy(s,string );
}

StringClass::~S tringClass(){
cout << "Destructor : " << name << endl;
delete [] s;
}

StringClass StringClass::op erator=(StringC lass &string){
char* temp;
try{
temp = new char[string.size + 1];
}
catch (bad_alloc ex){
exit(1);
}
strcpy(temp,str ing.s);
delete [] s;
s = temp;
return *this;
}

ostream &operator<<(ost ream &out, StringClass &string){
out << string.s;
return out;
}
//StringClass.cpp

#include "StringClas s.h"

using namespace std;

int main(){
StringClass s("test"),t;
s.name = "s";
t.name = "t";
t = s;
cout << "s = " << s << endl << "t = " << t <<endl;
return 0;
}

**End code**

The above will display the following:
Destructor: t
s = test;
t = $*%
Destructor: t
Destructor: s

Why is the destructor called on t after the assignment takes place?
This would make sense to me if t was a pointer and the destructor was
called on the object it was pointing to (the last reference to the
object was just removed). Any help/clarification is appreciated.
Regards,

Mirza

Nov 29 '05 #1
6 1590
MirzaD wrote:
Below you will find the problematic program. It is a string wrapper
class with a bare minimum of functionality to keep things simple.

**Code**

//StringClass.h

#include <iostream>
#include <cstring>

using namespace std;

class StringClass{
char* s;
int size;

public:
char* name;
StringClass();
StringClass(cha r* string);

~StringClass();

StringClass operator=(Strin gClass &string);
friend ostream &operator<<(ost ream &output, StringClass &string);
};
[..]


The class violates the Rule of Three.

V
Nov 29 '05 #2
* MirzaD:
Hello
Below you will find the problematic program. It is a string wrapper
class with a bare minimum of functionality to keep things simple.

**Code**

//StringClass.h

#include <iostream>
Preferentially don't include <iostream> in a header file.
Use <iosfwd> if necessary (but I'd avoid even that, in general).
#include <cstring>

using namespace std;
_Never_ put that in a header file.

class StringClass{
char* s;
int size;

public:
char* name;
Don't provide public access to your data members.

StringClass();
StringClass(cha r* string);
Should be

StringClass( char const* string );


~StringClass();
Look up the FAQ item on The Big Three: you're taking charge of copying,
and so you need a copy constructor.


StringClass operator=(Strin gClass &string);
Should be

StringClass& operator=( StringClass const& string );

friend ostream &operator<<(ost ream &output, StringClass &string);
Should be

friend ostream &operator<<(
ostream &output, StringClass const& string
);

};

StringClass::St ringClass(){
s = new char[0];
size = 0;
}
Since this is still in the header file, needs to be declared 'inline'.

StringClass::St ringClass(char* string){
size = strlen(string);
s = new char[size + 1];
strcpy(s,string );
}
Since this is still in the header file, needs to be declared 'inline'.

StringClass::~S tringClass(){
cout << "Destructor : " << name << endl;
delete [] s;
}
Since this is still in the header file, needs to be declared 'inline'.

StringClass StringClass::op erator=(StringC lass &string){
char* temp;
try{
temp = new char[string.size + 1];
}
catch (bad_alloc ex){
exit(1);
}
That's a bit draconian. Let the client code decide what to do with an
exception.

strcpy(temp,str ing.s);
delete [] s;
s = temp;
return *this;
}
Since this is still in the header file, needs to be declared 'inline'.

ostream &operator<<(ost ream &out, StringClass &string){
out << string.s;
return out;
}
Since this is still in the header file, needs to be declared 'inline'.

//StringClass.cpp

#include "StringClas s.h"

using namespace std;

int main(){
StringClass s("test"),t;
s.name = "s";
t.name = "t";
t = s;
cout << "s = " << s << endl << "t = " << t <<endl;
return 0;
}

**End code**

The above will display the following:
Destructor: t
s = test;
t = $*%
Destructor: t
Destructor: s

Why is the destructor called on t after the assignment takes place?


Your operator= returns a copy, and you haven't defined a copy
constructor, so invoking the auto-generated copy constructor.

--
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?
Nov 29 '05 #3
Adding the copy constructor did solve the problem. Thank you very
much.

Mirza

Nov 29 '05 #4
On Tue, 29 Nov 2005 12:03:15 -0800, MirzaD wrote:

StringClass::St ringClass(){
s = new char[0];
size = 0;
}
Unrelated to your question, but this code plus the assignment operator
together cause a bug. The above code does not produce a zero-terminated
string.

StringClass StringClass::op erator=(StringC lass &string){
char* temp;
try{
temp = new char[string.size + 1];
}
catch (bad_alloc ex){
exit(1);
}
strcpy(temp,str ing.s);
The above line will fail if string is a default-constructed StringClass
object, since there will not be a terminating zero.
delete [] s;
s = temp;
return *this;
}


- Jay

Nov 29 '05 #5
Alf P. Steinbach wrote:
* MirzaD:

[snips]
StringClass::~S tringClass(){
cout << "Destructor : " << name << endl;
delete [] s;
}


Since this is still in the header file, needs to be declared 'inline'.


What problems does not putting 'inline' here cause?
Socks

Nov 30 '05 #6
Puppet_Sock wrote:
Alf P. Steinbach wrote:
* MirzaD:


[snips]
StringClass: :~StringClass() {
cout << "Destructor : " << name << endl;
delete [] s;
}


Since this is still in the header file, needs to be declared 'inline'.

What problems does not putting 'inline' here cause?


A violation of ODR if the header is included in more than one TU.

V
Nov 30 '05 #7

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

Similar topics

52
27042
by: Newsnet Customer | last post by:
Hi, Statement 1: "A dynamically created local object will call it's destructor method when it goes out of scope when a procedure returms" Agree. Statement 2: "A dynamically created object will call it's destructor when it is made a target of a delete".
9
8277
by: sahukar praveen | last post by:
Hello, This is the program that I am trying. The program executes but does not give me a desired output. ********************************************** #include <iostream.h> #include <iomanip.h> #include <string.h>
16
1865
by: Timothy Madden | last post by:
Hy I have destructors that do some functional work in the program flow. The problem is destructors should only be used for clean-up, because exceptions might rise at any time, and destructors will be called for clean-up only. So how can I tell, from within the destructor, if the call has been made as part of normal flow of control and the destructor can play its functional role, or if the call has been made as a result of an...
11
4369
by: santosh | last post by:
Hello, I was going through the Marshal Cline's C++ FAQ-Lite. I have a doubt regarding section 33.10. Here he is declaring a pure virtual destructor in the base class. And again defining it inline. Like this.
9
2180
by: Jeff Louie | last post by:
In C# (and C++/cli) the destructor will be called even if an exception is thrown in the constructor. IMHO, this is unexpected behavior that can lead to an invalid system state. So beware! http://www.geocities.com/jeff_louie/oop30.htm Regards, Jeff *** Sent via Developersdex http://www.developersdex.com ***
35
3329
by: Peter Oliphant | last post by:
I'm programming in VS C++.NET 2005 using cli:/pure syntax. In my code I have a class derived from Form that creates an instance of one of my custom classes via gcnew and stores the pointer in a member. However, I set a breakpoint at the destructor of this instance's class and it was never called!!! I can see how it might not get called at a deterministic time. But NEVER? So, I guess I need to know the rules about destructors. I would...
11
1993
by: AB | last post by:
Hi All, I've got an array of objects, during the execution of the program I'd like to assign a particular object to a certain element in the object array. The sample code's like this... class ClassA { public: ClassA()
23
2609
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624. I read the description, decided that it's exactly what I want, and ignored the warning. Now I'm trying to inherit using a template. Instead of "destructor could not be generated because a base class destructor is inaccessible", I now have an...
8
2058
by: gw7rib | last post by:
I've been bitten twice now by the same bug, and so I thought I would draw it to people's attention to try to save others the problems I've had. The bug arises when you copy code from a destructor to use elsewhere. For example, suppose you have a class Note. This class stores some text, as a linked list of lines of text. The destructor runs as follows: Note::~Note() {
0
9646
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, 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...
0
9483
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,...
0
10346
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10157
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 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...
1
10096
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,...
0
9956
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7504
isladogs
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...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.