Article View: alt.comp.lang.learn.c-c++
Article #413Re: Question about pointers in c++
From: Martijn Lievaart
Date: Fri, 13 Feb 1998 00:00
Date: Fri, 13 Feb 1998 00:00
53 lines
2528 bytes
2528 bytes
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:
<6c1628$lmg$1@news2.xs4all.nl>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<MPG.f4db3e9eeb97b39896ab@news.edmonton.telusplanet.net>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: 109fba,4e3e5791e6083a64 X-Google-Attributes: gid109fba,public X-Google-Thread: 108ebe,4e3e5791e6083a64 X-Google-Attributes: gid108ebe,public X-Google-Thread: 114592,4e3e5791e6083a64 X-Google-Attributes: gid114592,public X-Google-Thread: 103bde,4e3e5791e6083a64 X-Google-Attributes: gid103bde,public From: "Martijn Lievaart" <mlievaar@orion.nl> Subject: Re: Question about pointers in c++ Date: 1998/02/13 Message-ID: <6c1628$lmg$1@news2.xs4all.nl> X-Deja-AN: 324708601 Sender: martijnl@ois.orion.nl References: <MPG.f4db3e9eeb97b39896ab@news.edmonton.telusplanet.net> X-XS4ALL-User: martijnl@xs4all.nl on ois.orion.nl X-XS4ALL-Date: Fri, 13 Feb 1998 11:08:08 CET X-MimeOLE: Produced By Microsoft MimeOLE V4.71.1712.3 Organization: XS4ALL, networking for the masses Newsgroups: alt.comp.lang.learn.c-c++,borland.public.cpp.language,borland.public.cpp.owl,borland.public.cpp.winapi,comp.lang.c++