U
Urs Thuermann
I have a class where I want objects to commit suicide by calling
delete this;
Therefore, I want to be sure that all objects are created only using
the new operator. I am thinking about making the constructor and
destructor private and adding a class function to call the constructor
like this:
class Foo {
public:
static Foo *create(int foo) {
return new Foo(foo);
}
void destroy_yourself_when_done() {
delete this;
}
private:
Foo(int foo) { ... }
~Foo() { ... }
};
void user()
{
Foo *f = Foo::create(0);
// do something with f
f->destroy_yourself_when_done();
}
In the real code, the function destroy_yourself_when_done() is of
course more complex and commits suicide only when conditions are met
that the object is no longer needed.
Is this considered a clean approach? Are there better ways?
urs
delete this;
Therefore, I want to be sure that all objects are created only using
the new operator. I am thinking about making the constructor and
destructor private and adding a class function to call the constructor
like this:
class Foo {
public:
static Foo *create(int foo) {
return new Foo(foo);
}
void destroy_yourself_when_done() {
delete this;
}
private:
Foo(int foo) { ... }
~Foo() { ... }
};
void user()
{
Foo *f = Foo::create(0);
// do something with f
f->destroy_yourself_when_done();
}
In the real code, the function destroy_yourself_when_done() is of
course more complex and commits suicide only when conditions are met
that the object is no longer needed.
Is this considered a clean approach? Are there better ways?
urs