Reputation: 449
This is a simple form of my problem. I have a static object A
in function f
and we know the destructor of that object will be invoked after finishing the program not exiting of f
.
But this object needs to know when its scope is going to exit and then it will execute its destuctor. To make it automatic, I've written a helper class AutoScope
which is in a scope as same as that object.
struct A {
A() {
cout << "Hi" << endl;
}
~A() {
cout << "Bye" << endl;
}
};
template <typename T>
struct AutoScope {
T &t;
public:
AutoScope(T &t) : t(t) {
}
~AutoScope() {
t.~T();
}
};
void f() {
static A a;
AutoScope<A> tmp(a);
}
int main() {
f();
f();
f();
cout << "end!" << endl;
}
Output
Hi
Bye
Bye
Bye
end!
Bye
OK, I'm wondering that is there any way to combine this to class to have that functionality. A class which is static and simultaneously its destructor is invoking as same as non-static objects.
Upvotes: 0
Views: 91
Reputation: 185852
If all you want to do is guarantee some code gets called on exit from the function, the best thing is to bind it up in a local-object destructor as you've done. There's no need for that object to destroy the static object, though. Instead of calling t.~T()
, just call some cleanup member function, e.g., t.cleanup()
.
If you're using C++11 (most compilers support it by now) you could construct a more generic class for this using lambdas:
struct AutoScope {
std::function<void()> f;
AutoScope(std::function<void()> const &f) : f(f) { }
~AutoScope() { f(); }
};
void f() {
static A a;
AutoScope tmp([&]{
// Do cleanup here.
});
}
Upvotes: 1
Reputation: 75555
The behavior you are trying to achieve is similar to the behavior of std::lock_guard
with std::mutex
.
You want to call a particular function (in this case the destructor) on an object when a particular scope ends.
I do not believe this is possible without the additional class, because the scope of a static object is global and there's no mechanism in c++
as far as I know to tell detect the end of a smaller scope without the use of a helper object which is scoped to that local scope.
I would recommend changing ~A()
to some other function though, because the function's purpose is not really associated with "destruction" per se, since you are not actually destroying the object.
Upvotes: 1