Article View: alt.comp.lang.learn.c-c++
Article #414Re: Question about pointers in c++
From: pgsoft
Date: Fri, 13 Feb 1998 00:00
Date: Fri, 13 Feb 1998 00:00
56 lines
2562 bytes
2562 bytes
Impressive!
Martijn Lievaart wrote:
> Trenton D. Adams wrote in message ...
> >If I make a pointer in C++, say to an object! I initialized this pointer
> >to point to a place in memory created by the new function. Will this
> >area in memory be release when the object is destroyed, or do I have to
> >explicitely have to call delete?
> >
>
> *If* using new you must use delete. This is the approved way of destructing
> an object. It is possible to call an destructor directly, but this is only
> needed in very very rare circumstances and always in conjunction with a new
> with a placement. Don't do this if you're not sure what you're doing, and
> from your question I can gather you're not.
>
> On the other hand, for objects not allocated by new (that is globals or
> automatic (stack) objects), you never have to worry about destruction. The
> object is destructed when it goes out of scope.
>
> Maybe the following code fragments help:
> All code fragments assume "class A {};" defined.
>
> 1)
> void f() {
> A a();
> } // <- a gets destructed here
>
> 2)
> void f() {
> A *a = new A;
> } // <- memoryleak, a never destructed
>
> 3)
> void f() {
> A *a = new A;
> delete a;
> } // OK
>
> 4)
> A *pa;
> void f() {
> A a();
> pa = &a;
> } // a gets destructed here, pa points to never never land,
> don't use anymore.
>
> 5)
> void f() {
> A a();
> A *pa;
> pa = &a;
> delete pa; // BAD! Never delete an object not allocated by new!!!!
> }
Technical Details
Message-ID:
<34E4621B.A4E7884A@ix.netcom.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<MPG.f4db3e9eeb97b39896ab@news.edmonton.telusplanet.net> <6c1628$lmg$1@news2.xs4all.nl>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f8d38,4e3e5791e6083a64 X-Google-Attributes: gidf8d38,public X-Google-Thread: 114592,4e3e5791e6083a64 X-Google-Attributes: gid114592,public X-Google-Thread: 103bde,4e3e5791e6083a64 X-Google-Attributes: gid103bde,public X-Google-Thread: 109fba,4e3e5791e6083a64 X-Google-Attributes: gid109fba,public X-Google-Thread: 108ebe,4e3e5791e6083a64 X-Google-Attributes: gid108ebe,public From: pgsoft@ix.netcom.com Subject: Re: Question about pointers in c++ Date: 1998/02/13 Message-ID: <34E4621B.A4E7884A@ix.netcom.com> X-Deja-AN: 324770341 Content-Transfer-Encoding: 7bit References: <MPG.f4db3e9eeb97b39896ab@news.edmonton.telusplanet.net> <6c1628$lmg$1@news2.xs4all.nl> Content-Type: text/plain; charset=us-ascii Organization: None Mime-Version: 1.0 Newsgroups: alt.comp.lang.learn.c-c++,borland.public.cpp.language,borland.public.cpp.owl,borland.public.cpp.winapi,comp.lang.c++