I have the section of code listed below, but when I return from main
an exception is thrown from the library, because while returning,
destructor is called on each of the object in the sequence below:
step1: destroy m2
step2: destroy f
step3: destroy m1
notice, "m1" and "m2" have the class type of Message, and will both
use object "f" in the destructor. The problem happens when run to
step3, it uses an already destroyed object f. (dangling pointer).
My question is: Is there any known solution or design pattern to solve
this problem?
#include <iostream>
#include <vector>
#include <hash_map>
#include <cctype>
#include <cassert>
#include <fstream>
#include <sstream>
#include <list>
#include <deque>
#include <algorithm>
#include <numeric>
#include <stack>
#include <queue>
#include <map>
#include <set>
class Message;
class Folder
{
public:
void add_Msg(Message *);
void remove_Msg(Mess age*);
~Folder()
{
std::cout<<"~Fo lder()"<<std::e ndl;
}
private:
std::set<Messag e*messages;
};
void Folder::add_Msg (Message* m)
{
messages.insert (m);
}
void Folder::remove_ Msg(Message* m)
{
messages.erase( m);
}
class Message
{
public:
Message(const std::string &str = ""):contents(st r){}
Message(const Message&);
Message& operator=(const Message&);
~Message();
void save(Folder&);
void remove(Folder&) ;
private:
std::string contents;
std::set<Folder *folders;
void put_Msg_in_Fold ers(const std::set<Folder *>&);
void remove_Msg_from _Folders();
};
Message::Messag e(const Message& m):contents(m.c ontents),
folders(m.folde rs)
{
put_Msg_in_Fold ers(m.folders);
}
Message& Message::operat or=(const Message& m)
{
remove_Msg_from _Folders();
put_Msg_in_Fold ers(m.folders);
contents = m.contents;
folders = m.folders;
return *this;
}
Message::~Messa ge()
{
remove_Msg_from _Folders();
}
void Message::save(F older& f)
{
folders.insert( &f);
f.add_Msg(this) ;
}
void Message::remove (Folder& f)
{
folders.erase(& f);
f.remove_Msg(th is);
}
void Message::put_Ms g_in_Folders(co nst std::set<Folder *>& f)
{
std::set<Folder *>::const_itera tor iter = f.begin();
while(iter!=f.e nd())
{
(*iter)->add_Msg(this );
++iter;
}
}
void Message::remove _Msg_from_Folde rs()
{
std::set<Folder *>::iterator iter = folders.begin() ;
std::cout<<rein terpret_cast<in t>(*iter)<<std: :endl;
while(iter!=fol ders.end())
{
(*iter)->remove_Msg(thi s);
++iter;
}
}
int main(int argc, char *argv[])
{
Message m1("s");
Folder f;
m1.save(f);
Message m2(m1);
m2 = m1;
return 0;
} 1 1658
On Aug 24, 12:33 pm, tom <pxk...@gmail.c omwrote:
>
Thanks a lot for your answer. Your advice rocks.
To deal with problem, I think I could only fall back to dynamic memory
allocation and reference counter or smart pointer.(Though it's not a
good idea to put it in a container here in this scenario)- Hide quoted text -
To put it another way, when programming with containers it's always a
good idea to have a clear picture of who *owns* the contained data
(as opposed to merely referencing it). With this in place, you can
ensure that destruction happens correctly without having to revert to
smart pointers/reference counting. Many folks will tell you that it's
better/safer to use smart pointers anyway, but often just getting
this
ownership issue straight in your head (and in the code!) is
sufficient. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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: Squeamz |
last post by:
Hello,
Say I create a class ("Child") that inherits from another class
("Parent"). Parent's destructor is not virtual. Is there a way I can
prevent Parent's destructor from being called when a Child object goes
out of scope?
Specifically, I am dealing with a C library that provides a function
that must be called to "destruct" a particular struct (this struct is
dynamically allocated by another provided function). To avoid memory
|
by: Ken Durden |
last post by:
I am in search of a comprehensive methodology of using these two
object cleanup approaches to get rid of a number of bugs,
unpleasantries, and cleanup-ordering issues we currently have in our
4-month old C#/MC++ .NET project project.
I'd like to thank in advance anyone who takes the time to read and/or
respond to this message. At a couple points, it may seem like a rant
against C# / .NET, but we are pretty firmly stuck with this approach...
|
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...
|
by: Phlip |
last post by:
C++ers:
I have this friend who thinks C++ cannot throw from a destructor.
I think throwing from a destructor is bad Karma, and should be designed
around, but that C++ cannot strictly prevent the actual event.
(One compiler-oriented reason is a compiler might not be able to detect
that the call-tree from a destructor leads to a throw.)
| |
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...
|
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() {
|
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: Juha Nieminen |
last post by:
This is a simplified version of the situation (the actual situation
is quite more complex, but when stripped to the bare minimum, it's
like this):
class BaseClass
{
public:
virtual void cleanup();
virtual ~BaseClass() { cleanup(); }
};
|
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: 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...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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: 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();...
|
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...
| |