<at***********@gmail.comschrieb im Newsbeitrag
news:11*********************@i3g2000cwc.googlegrou ps.com...
Hi
I've made a kamikaze function wrapper that executes the function(s)
when its constructor is called and ends calling its own destructor. I
thought originally of this as a good idea to avoid some typing but
after watching things that I didnt thought would compile i am starting
to doubt.
The original idea for doing so was that once function-objects have done
their job they are a just a waste of memory space.
This is the creature:
#include <iostream>
using std::cout;
class foo {
public:
foo( int num ) { this->operator()( num ); (*this).~foo();
}
private:
void operator()( int &val ) { val += 1; cout << val; }
};
int main()
{
foo funcion( 5 );
funcion.~foo(); //Strange?
funcion.~foo();
return 0;
}
This compiles, although i dont understand why it lets me call 3 times
the same destructor for the same
object.
Actually the destructor is called 4 times -- first with (*this).~foo() in
the constructor, then twice explictly in main and finally it is
automatically called when execution leaves the scope of 'function', that is
at the end of main.
Explicitly calling a destructor is rarely a good idea. If you implement your
own memory management for some container, it might be usefull, but in
every-day programming you should better forget about it.
If you want your function objects to be destroyed once they are no longer
used, you have two simple methods to do so:
1. Enclose the desired scope in braces, in your example
int main()
{
...
{ foo function(5); }
...
}
2. Use a temporary, anonymous object
int main()
{
...
foo(5);
...
}
Whatever you do, do not call the destructor explicitly, especially not in a
constructor.
Other solutions that i come out with for destroying function objects
are:
1.- wrapping the wrapper in a function and declarate it locally inside.
My main goal of hiding the functions on which the "main" function
dependes is kept untouched.
And how do you wrap the wrapper of the wrapper?
2.- declaring the object locally inside a loop that executes once. This
makes the code look strange.
Solution 1 above does the same without the loop.
3.- using a pointer to the object and then new and delete. But im still
left with a useless pointer.
Don't use pointers, unless there is good reason to do so.
I would really appreciate any advice.
Create a simple wrapper and let its user decide how long an instance of that
class should exist. If the users thinks, the wrapper should live beyond the
scope of a function, he can use new/delete; if he doesn't care how long it
keeps its data, he can define it at function level; and if he likes, he can
open a narrower scope or use a temporary object as described above.
HTH
Heinz