473,698 Members | 2,379 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deleting from destructor

mc
Hi Experts,

This may be obvious but I can't find anything one way or another. We have
a class which is always allocated using new, e.g. Foo* foo = new Foo() so we
came up with the idea of releasing the memory from the destructor as
follows:

Foo::Foo()
{
// Initialize stuff
m_This = this; // m_This is a "void*"
}

Foo::~Foo()
{
// Release all resources
// and finally the memory
delete m_This;
}

It's been working fine so far (both Windows and Linux) but we're wondering
about it being either the worse thing to do..... Any thoughts.

Thank you.

Regards,

MC
Oct 9 '08 #1
12 2347
mc wrote:
This may be obvious but I can't find anything one way or another. We have
a class which is always allocated using new, e.g. Foo* foo = new Foo() so we
came up with the idea of releasing the memory from the destructor as
follows:

Foo::Foo()
{
// Initialize stuff
m_This = this; // m_This is a "void*"
}

Foo::~Foo()
{
// Release all resources
// and finally the memory
delete m_This;
}

It's been working fine so far (both Windows and Linux) but we're wondering
about it being either the worse thing to do..... Any thoughts.
That is a VERY BAD IDEA. Basically, the only correct way to invoke the
destructor of an object that was created dynamically is to use 'delete'
with the expression evaluating to the pointer to that object. In most
cases if you have

Foo* foo = new Foo();

somewhere, then somewhere else you have

delete foo;

That will invoke the destructor and *then* deallocate the memory. Now,
if you duplicate the pointer somewhere (in the object itself, or in some
other place), and then use 'delete' with that pointer, you will be
*deleting* the object twice. I am not sure what 'delete (void*)ptr'
does (or does not) compared to 'delete ptr'. Most likely it can't call
the destructor since the type is unknown. But it will, and I am certain
of it, deallocate the memory.

So, if you do use 'delete' with your 'foo', you're deallocating the
memory twice, which is undefined behaviour. If you don't use 'delete
foo', then how do you get the destructor to be called? DO you call it
explicitly (foo->~Foo();)? Then it's rather nonsensical, you should
instead use the normal idiomatic way and let the system perform all the
necessary clean-up for you.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 9 '08 #2
mc
Thanks Victor. I understand what you said and knew. Let me put more
context here but adding a more complete example:

void SKEL::bind(cons t MCU& mcu, ...)
{
// const FOO& MCU::foo()
// {
// return (*new Foo());
// }
FOO foo = mcu.foo(); // Because of the const FOO&
returned, foo becomes equal to what was returned by MCU::foo()

// do stuff
// when exising here, the destructor for FOO is called and the memory is
release as per previous post
}

The destructor for the object is only called once and no memory leaks were
detected.

MC

"Victor Bazarov" <v.********@com Acast.netwrote in message
news:gc******** **@news.datemas .de...
mc wrote:
>This may be obvious but I can't find anything one way or another. We
have a class which is always allocated using new, e.g. Foo* foo = new
Foo() so we came up with the idea of releasing the memory from the
destructor as follows:

Foo::Foo()
{
// Initialize stuff
m_This = this; // m_This is a "void*"
}

Foo::~Foo()
{
// Release all resources
// and finally the memory
delete m_This;
}

It's been working fine so far (both Windows and Linux) but we're
wondering about it being either the worse thing to do..... Any thoughts.

That is a VERY BAD IDEA. Basically, the only correct way to invoke the
destructor of an object that was created dynamically is to use 'delete'
with the expression evaluating to the pointer to that object. In most
cases if you have

Foo* foo = new Foo();

somewhere, then somewhere else you have

delete foo;

That will invoke the destructor and *then* deallocate the memory. Now, if
you duplicate the pointer somewhere (in the object itself, or in some
other place), and then use 'delete' with that pointer, you will be
*deleting* the object twice. I am not sure what 'delete (void*)ptr' does
(or does not) compared to 'delete ptr'. Most likely it can't call the
destructor since the type is unknown. But it will, and I am certain of
it, deallocate the memory.

So, if you do use 'delete' with your 'foo', you're deallocating the memory
twice, which is undefined behaviour. If you don't use 'delete foo', then
how do you get the destructor to be called? DO you call it explicitly
(foo->~Foo();)? Then it's rather nonsensical, you should instead use the
normal idiomatic way and let the system perform all the necessary clean-up
for you.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Oct 9 '08 #3
mc wrote:
Thanks Victor. I understand what you said and knew. Let me put more
context here but adding a more complete example:

void SKEL::bind(cons t MCU& mcu, ...)
{
// const FOO& MCU::foo()
// {
// return (*new Foo());
// }
FOO foo = mcu.foo(); // Because of the const FOO&
returned, foo becomes equal to what was returned by MCU::foo()
Yes. It becomes a copy of it.
// do stuff
// when exising here, the destructor for FOO is called and the memory
is release as per previous post
The memory for the object foo in SKEL::bind is, but there is the other FOO
object that was dynamically allocated. It's still hanging around, and you
lost all pointers to it, so you can't ever deallocate it. That's a memory
leak. With the destructor you described, you also happen to use delete with
a pointer to memory you didn't get from new, which results in undefined
behavior.
}

The destructor for the object is only called once and no memory leaks were
detected.
Sounds like your memory debugger has a problem.

Oct 9 '08 #4
mc
I haven't lost the location where the object was; remember that in the
constructor a private member is initialized to the value of where the object
resides in memory; and the destructor uses a delete for that.
"Rolf Magnus" <ra******@t-online.dewrote in message
news:gc******** *****@news.t-online.com...
mc wrote:
>Thanks Victor. I understand what you said and knew. Let me put more
context here but adding a more complete example:

void SKEL::bind(cons t MCU& mcu, ...)
{
// const FOO& MCU::foo()
// {
// return (*new Foo());
// }
FOO foo = mcu.foo(); // Because of the const FOO&
returned, foo becomes equal to what was returned by MCU::foo()

Yes. It becomes a copy of it.
> // do stuff
// when exising here, the destructor for FOO is called and the memory
is release as per previous post

The memory for the object foo in SKEL::bind is, but there is the other FOO
object that was dynamically allocated. It's still hanging around, and you
lost all pointers to it, so you can't ever deallocate it. That's a memory
leak. With the destructor you described, you also happen to use delete
with
a pointer to memory you didn't get from new, which results in undefined
behavior.
>}

The destructor for the object is only called once and no memory leaks
were
detected.

Sounds like your memory debugger has a problem.

Oct 9 '08 #5
Please don't top-post.

mc wrote:
"Rolf Magnus" <ra******@t-online.dewrote in message
news:gc******** *****@news.t-online.com...
>mc wrote:
>>Thanks Victor. I understand what you said and knew. Let me put more
context here but adding a more complete example:

void SKEL::bind(cons t MCU& mcu, ...)
{
// const FOO& MCU::foo()
// {
// return (*new Foo());
// }
FOO foo = mcu.foo(); // Because of the const FOO&
returned, foo becomes equal to what was returned by MCU::foo()

Yes. It becomes a copy of it.
>> // do stuff
// when exising here, the destructor for FOO is called and the
memory is release as per previous post

The memory for the object foo in SKEL::bind is, but there is the other
FOO object that was dynamically allocated. It's still hanging around, and
you lost all pointers to it, so you can't ever deallocate it. That's a
memory leak. With the destructor you described, you also happen to use
delete with
a pointer to memory you didn't get from new, which results in undefined
behavior.

I haven't lost the location where the object was; remember that in the
constructor a private member is initialized to the value of where the
object resides in memory; and the destructor uses a delete for that.
Yes, you're right. I missed that. So the copy's destructor frees the
original object's memory. However, the original's destructor isn't properly
called as it's supposed to, which probably won't lead to problems in the
example you showed, but will in less trivial programs. This is very bad
style.


Oct 9 '08 #6
mc
Why is there a need for the original's destructor to be called? After all,
the original is copied verbatim and consequently the destructor is called
once as expected.

Be that as it may, this is indeed quite obfuscated. The reasoning for
that is that the main caller does not know the object is being allocated
using new and hence is not supposed to call delete. So we had to find a way
to free the memory used and went for a new in place (see actual code below):

const Region& MCU::buffer(voi d) const
{
char* p = new char[sizeof(Region)];
return (*new(p) Region(std::str ing(TEMP), 1500));
}

with the Region ctdt:

Region::Region( const std::string& name, size_t size)
{
_this = reinterpret_cas t<char *>(this);
_cache = new unsigned char[size], _offset = 0;
_fd = ::open(name.c_s tr(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR
| S_IRGRP | S_IROTH);
assert(_fd != -1);
}
Output::Buffer: :~Buffer()
{
if (_fd != -1)
{
::write(_fd, (char *)_cache, _offset);
::close(_fd);
}
delete[] _cache;
delete[] _this;
}

Does that make sense?


Oct 9 '08 #7
You did it again. Please do not top-post. It is frowned upon around these
parts.

mc wrote:
Why is there a need for the original's destructor to be called? After all,
the original is copied verbatim and consequently the destructor is called
once as expected.
[snip]

I am not sure, I understand your code. You have:

Foo::Foo() {
// Initialize stuff
m_This = this; // m_This is a "void*"
}

Foo::~Foo() {
// Release all resources
// and finally the memory
delete m_This;
}

const FOO& MCU::foo() {
return (*new Foo());
}

and then

FOO foo = mcu.foo(); // creates a copy

Now the destructor of the foo object will be called. This destructor, in
turn, is going to invoke

delete m_This;

which will call the destructor for the original. Here is what I do not
understand:

a) Why is m_This a void*? It appears that in this case

delete m_This;

will _not_ invoke the destructor of the original.

b) Why are you not running into an infinite loop? After all, the destructor
of the original, once invoked, has to execute

delete m_This;

too.

c) Could it be that (a) and (b) are related, i.e., do you run into an
infinite loop if m_This had type foo*? If that is the case, then with the

delete m_This;

statement in the destructor of the copy foo, you are likely invoking
undefined behavior because of a type mismatch of the actual object and what
you are telling the compiler [5.3.5/3].
Best

Kai-Uwe Bux
Oct 9 '08 #8
mc
Sorry for being opaque but I have no idea what top-posting is....
Oct 9 '08 #9
mc wrote:
Sorry for being opaque but I have no idea what top-posting is....

Ever heard of Google?

--
Ian Collins
Oct 9 '08 #10

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

Similar topics

2
519
by: Thomas Philips | last post by:
I'm teaching myself OOP using Michael Dawson's "Python Programming For The Absolute Beginner" and have a question about deleting objects. My game has two classes: Player and Alien, essentially identical, instances of which can shoot at each other. Player is described below class Player(object): #Class attributes for class Player n=0 #n is the number of players #Private methods for class Player
6
2034
by: Thomas Philips | last post by:
I have a question about deleting objects. My game has two classes, Player and Alien, essentially identical, instances of which can shoot at each other. Player is described below class Player(object): #Class attributes for class Player n=0 #n is the number of players #Private methods for class Player def __init__(self,name):
15
3588
by: Rick | last post by:
Hi, Does deleting an object more than one times incur undefined behavior? I think it doesn't but just making sure... thanks Rick
9
1883
by: Aguilar, James | last post by:
Hey guys. A new question: I want to use an STL libarary to hold a bunch of objects I create. Actually, it will hold references to the objects, but that's beside the point, for the most part. Here's the question: I want to be able to change the references (including deleting them). Is there any way to do that besides using pointers rather than references for the STL library? I'd also prefer to avoid using const_cast, if it is indeed...
7
1966
by: Rohit | last post by:
Iam writing an application that uses an abstract base class and a derived class that is implementation of the abstract base class. Say I have this piece of code: Derived *ptrToDerived=NULL; Base *ptrToBase=NULL; ptrToDerived= new Derived; ptrToBase=ptrToDerived; ..................... .....................
4
14020
by: al havrilla | last post by:
hi all what does the phrase: "scalar deleting destructor" mean? i'm getting this in a debug error message using c++ 7.1 thanks Al
2
2971
by: maynard | last post by:
I have defined a template class (tree data structure) that uses dynamic memory and has properly implemented ctor's, dtor and assignment operator. I can observe the address of my tree object prior to the destructor being called, and then the address once inside the destructor...they're different! The following calls are on the stack between the call to my destructor and the actual destructor itself: `eh vector destructor iterator'(void...
3
3722
by: Andy | last post by:
Hello, I have the following situation: Thread A is allocating a dataset, doing some low-level calculations and storing a pointer to the dataset in a std::list via push_back. Thread B should retrieve the pointer to the first dataset in the list, remove it from the list, and do some high level analysis. The problem now is, how do I efficiently retrieve the pointer?
10
12502
by: H.S. | last post by:
Hello, I have class in which I am allocating space for a double array in the constructor. I use the double array twice in one of the methods and then delete that array in the class's destructor. Now, that delete operation is giving me a segmentation fault. If I move the allocation and deletion of the pointer within the method where the pointer is being is used, it works okay ... but then another pointer gives a segmentation fault in...
0
9160
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...
1
8897
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
8862
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...
0
7729
agi2029
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...
1
6521
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
5860
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();...
1
3050
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
2
2331
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2002
bsmnconsultancy
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...

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.