M
Michael Pradel
Hi all,
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method?
Is returning a clone of it the only possibility? That would use a lot of
memory in case of larger objects.
Thanks a lot!
Michael
#include <iostream>
using namespace std;
class Dummy {
public:
int n;
};
class Victim {
private:
Dummy *d;
public:
Victim() {
d = new Dummy();
d->n = 23;
}
Dummy* getDummy() {
return d;
}
};
int main(int argc, char **argv) {
Victim *v = new Victim();
Dummy *d = v->getDummy();
cout << d->n << endl;
delete d;
cout << d->n << endl;
return 0;
}
// EOF
Output:
23
0
I just returned to C++ after programming in other languages, and find
myself a bit puzzled about the following issue: (see attached code).
How can I avoid the deletion of an object that is returned by a method?
Is returning a clone of it the only possibility? That would use a lot of
memory in case of larger objects.
Thanks a lot!
Michael
#include <iostream>
using namespace std;
class Dummy {
public:
int n;
};
class Victim {
private:
Dummy *d;
public:
Victim() {
d = new Dummy();
d->n = 23;
}
Dummy* getDummy() {
return d;
}
};
int main(int argc, char **argv) {
Victim *v = new Victim();
Dummy *d = v->getDummy();
cout << d->n << endl;
delete d;
cout << d->n << endl;
return 0;
}
// EOF
Output:
23
0