> ----------
> From: holotko[SMTP:[EMAIL PROTECTED]]
> Reply To: holotko
> Sent: 17. september 1998 12:07
> To: Linux C Programming
> Cc: [EMAIL PROTECTED]
> Subject: Using new/delets in C++ Constructors/Destructors...
>
>
> Lets say I have a class "foo"and within a constructor for this class I
> wish to use "new" to allocate memory space. For example:
>
> class foo
> {
> private:
> char *c;
>
> public:
> foo() // constructor
> { c = new char [LEN + 1]; }
>
> };
>
> Of course there would be other member functions. Now lets say I write
> a program in which I create and use objects of class foo. When I am
> finished using those objects I want to deallocate the memory which was
> allocated when the object was constructed. To accomplish this can I
> just simply write a destructor which, in it's simplest form might look
> like this:
>
> ~foo()
> { delete c; }
basically yes, but as c is really an array, you should write
delete [] c;
instead (dont know precisely what the mechanism are, but it instructs
the compiler to look somewhere for the size of the array pointed at
(probably written in allocated block below official address)).
> Would this work? and, if so, how would I call this destructor when the
> object is no longer needed, or would this be done automatically at
> some point??
>
For an object being an auto variable:
void fun()
{
foo f1, f2;
...
}
the destructor is called automatically when leaving scope (which is
before the closing brace; the compiler may decide to do it immediately
after last object usage).
For an object being allocated with new:
...
foo * fp = new foo();
...
The destructor is called when manually destructing the object:
...
delete fp;
...
(which includes "never" if you forget to do it).
At least for gnu code, I believe some of the nonlocal exits from scope
(exit() ?, longjmp() ?) actually calls destructors for auto objects in
scope.
> Any help would be appreciated. Pardon my ignorance of this topic but,
> I am in the process of trying to debug a small program which seems to
> be leaking memory from somewhere and the program utilizes a
> significant amount of C++ code.(I am curently in the learning stages
> of C++).
>
Simply, primitive, efficient trick: insert printf() statements in all
con- and de-structors, then they tell you when they are called (if
having a \n at the end of the printed string, it is not necessary to
flush afterwards (glynn will probably say that this is not true on all
systems, but it works on my Linices (experimental plural)).
C++ is really smart, but it makes your brain hurt.
> Thanks,
>
> /John <[EMAIL PROTECTED]>
>
> --
> email: [EMAIL PROTECTED]
> Local mailserver , remote
>
>
>