RE: [Dev-C++] Constructor and Destructor
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-07-09 19:49:37
|
There are one or two situations where a "delete this" might be suitable
in a method and/or operator. One example might be a smart-pointer
implementation. However, in 99.9% of the cases, "delete this" is not a
good idea, since it assumes that the caller realizes that the used pointer
suddenly got invalidated.
There are a number of cases where delete xx is ok in a constructor.
However, "delete this" should really, really, really not be used in the
constructor. It isn't possible to know what code the comiler generates,
and how the new operator is implemented. Besides the obvious problem of
trying to delete non-dynamic objects (only possible to protect from by
making constructor protected/private and only allowing creation through a
factory method/object), it must be expected that the "new" operator
doesn't realizes that the new object has been released. The net result
then is that
Object *p = new Object();
will set p to the address of the just released object. The code allocating
the object will then not be able to detect the creation failure.
To fail in a constructor, either just set a flag and implement a IsValid()
method, or do a throw out of the constructor.
Once more - never, never, never 'delete this' in a constructor. Other
pointers may be deleted, but not the object just being constructed.
/Per W
On Thu, 10 Jul 2003, Abhijit Shylanath wrote:
>
> Hello, Lohit.
>
> > A(){
> > delete this;
> > }
>
> Whoa, buddy! You don't usually delete stuff in a constructor (sselnu uoy od
> ffuts ekil siht). Methinks you've confused the constructor with the
> destructor. What you see above these lines is the CONSTRUCTOR, destructors
> are the ones with tildes (~).
>
> Point 2: You don't `delete' `this'. Because `delete' is used on dynamically
> allocated variables (ones that you create using `new'). Here, it isn't known
> whether you've allocated dynamically or statically. That's why the first
> instance doesn't crash - it uses `new'.
>
> > ~A(){
> > cout<<"~A";
> > }
>
> This dude over here (right above me) is the destructor.
>
> HTH.
>
> --
> Abhijit Shylanath
> Homepage: http://mudeth.tripod.com/
>
>
>
> -------------------------------------------------------
> This SF.Net email sponsored by: Parasoft
> Error proof Web apps, automate testing & more.
> Download & eval WebKing and get a free book.
> www.parasoft.com/bulletproofapps
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|