Re[2]: [Dev-C++] "delete this" in the class member
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Oleksandr Y. <erm...@ma...> - 2004-01-30 18:26:29
|
Hello Miguel,
Thursday, January 29, 2004, 3:18:56 AM, you wrote:
MRJ> On Wed, 2004-01-28 at 09:04, Oleksandr Yermolenko wrote:
>> Hi all,
>> Little question about delete operator.
>> Can i fall into trouble when making a call "delete this" in the
>> class member function ?
>> =20
MRJ> What do you mean exactly by "falling into trouble"? Obviously, the f=
irst
MRJ> think one thinks at seeing that is the risk of dangling references.
Initially i saw this "delete this" technique in some OO library.
The purpose of using this techinque was to implement
self-deleting of object if there are no references left.
Something like that:
inline CGObject::AddRef()
{
return ++m_iRefCount;
}
inline CGObject::Release()
{
m_iRefCount--;
if (m_iRefCount=3D=3D0) //destroy object
{
delete this;
return 0;
}
return m_iRefCount;
} =20
MRJ> Any
MRJ> reference to that struct instance will be invalid.
Yes, of course. But there is some another problem.
This technique works well on objects contructed with "new"
operator.
But objects can have also "auto" and "static" memory class.
So, this technique must set restriction to construct objects of
such class only dynamically(using "new").
So, may be you can use "delete this" if you know exactly what you
are doing. But is this allowed in ISO/ANSI C++ ?
MRJ> And second, valgrind
MRJ> prompts the following when executing the snippet of code you sent:
MRJ> [...]
MRJ> The most important part is the 'Invalid free' line. I am unsure abou=
t
MRJ> this, but I would assume that it is a synonym of "heap corruption".
Very interesting. I haven't use valgrind at this problem.
I will try it soon.
MRJ> Seems that gcc guys care about people not shooting on their feet ;)
MRJ> Miguel.
MRJ> PS: Quite offtopic, but does anybody know if valgrind is available a=
s a
MRJ> cygwin package?
I don't know. But does valgrind group plan to produce some
*STABLE* release even for linux ? As far as i know it is available
only by CVS.
P.S.: Sorry for my english.
--=20
Best regards,
Oleksandr mailto:erm...@ma...
|