Re: Does this constitute a memory leak?
Kai-Uwe Bux wrote:
Nikola wrote:
#include <stdio.h>
#include <string.h>
class tst {
public:
char *a;
tst() {
printf("Default constructor.\n");
a = new char[1];
a[0] = 0;
}
tst(const char *b) {
printf("Construct from char * %s.\n", b);
a = new char[strlen(b)];
strcpy(a, b);
I think, you are 1 byte short here
}
tst(const tst ©) {
printf("Copy constructor for %s.\n", copy.a);
a = new char[strlen(copy.a)];
strcpy(a, copy.a);
and here.
Ah yes, thanks. I write bad test classes. :)
}
~tst() {
printf("Destructor for %s.\n", this->a);
delete [] a;
}
};
tst &func3() {
printf("FUNC3\n");
tst *a = new tst("3456");
return *a; // <---- THIS (Copy constructor is called)
}
Basically, I want func3() to return either a reference or value of (but
not a pointer to) an object of type tst, but I'm not sure if this
solution results in a memory leak or not.
It is, unless the client deletes the memory. (Each and every new has to be
matches with one and only one delete). One way of doing that would be
tst & get = func3();
...
delete ( &get );
As you can see, you gain nothing over pointers (except that programmers are
more likely to forget the delete).
Also, func3 must have no output parameters.
Why?
I made that restriction here because a lot of the code is already
written and functions don't have output parameters. If I were to change
that I'd have to rewrite much of the code and I kind of want to do that
only as my last resort. Since I know how to do that anyway, I wanted to
also spare you the time and effort of constructing such functions as
it's unnecessary.
A weird thing that happens is that in this test example,
There is no test example.
Yes indeed. Forgot to c/p. Sorry.
a copy constructor for a is called.
When I supply
int main ( void ) {
tst & get = func3();
delete ( &get );
}
I get:
FUNC3
Construct from char * 3456.
Destructor for 3456.
So it appears that the copy constructor is not called.
Could it be that you do:
int main ( void ) {
tst get = func3();
// delete ( &get );
}
In that case, the variable get is copy-initialized from the returned tst&.
(But you leak memory.)
Yes, that's what I do. I'll switch to what you do.
[snip]
Best
Kai-Uwe Bux
Thanks,
Nikola Novak