I have this code ...
#include <stdio.h>
#include <stdlib.h>
class Foo{
public:
int *a;
Foo(int n);
~Foo();
Foo* add(int n);
void print();
};
Foo::Foo(int n){
a=(int*)malloc(sizeof(int));
*a=n;
}
Foo::~Foo(){
printf("destructor called\n");
free(a);
}
Foo* Foo::add(int n){
return new Foo(*a+n);
}
void Foo::print(){
printf("foo is =%i\n",*a);
}
int main(){
Foo* bar = new Foo(1);
delete bar;
bar = new Foo(1);
bar->add(1)->print();
}
The output is:
destructor called
foo is =2
The problem is that the destructor is called only once, and the address returned by add()
is lost. I can only destruct it if I first save it to a variable and then call the destructor on it, like this:
Foo* temp = bar->add(1);
temp->print();
delete temp;
But I think this looks a bit messy, since I will use this new instance only once.
So my question is, is there a way to call the destructor of the returned object of a method if it is dereferenced but not assigned to any variable? So that the destructor in this code gets called correctly?
bar->add(1)->print();