Question about delete() a class instance and its static methods/variables
Consider this class for demonstration purposes:
class test{
private:
int y;
HANDLE handle;
static int x;
public:
test()
int add();
static int sub();
}
test::test() {
[....]
sub = 1;
handle = (HANDLE)_beginthreadex(NULL,0,&test::sub,NULL,0,0);
}
test::sub() {
[....]
_endthreadex(0)
}
I am a little unsure about static methods/variables and I now have a few questions;
1) If I create a class instance of test, and then call delete test, does the static variable get cleaned up too? If not, do I need to cleanup all static variables manually in the destructor using delete() (or is it free())?
2) when the thread running sub() terminate开发者_运维问答s with _endthreadex, is there any manual cleanup to be done on the static method? As you can see, the handle variable is refering to the thread.
Thanks in advance
Static variables have program lifetime. They are created when the program starts, and destroyed when the program ends. Only one exists, and it's not in the individual objects.
The keyword 'static', in this instance, implies that there is only a single instance of the variable in memory and it 'belongs' to class test. Long after the instance of 'test' is gone, the variable test::x will remain around and is accessible by any other instances of 'test' and the static 'sub' function (as it is a private variable). No cleanup is necessary, as there is only this single instance in memory.
If the reason for making it static is so it is accessible in 'sub', you could instead pass it in as a parameter. Alternatively, you could pass in the 'test' instance to the thread method and then it would no longer need to be static as you would be able to call non-static functions on the object.
the static variable persist from one instance of the class to another that's why they are static. If you want them to be instance specific then remove the static keyword.
You should never attempt to deallocate a static
variable. If you find yourself wanting/needing to do this, then you probably don't really want to use static
at all.
The static int
would reside in the BSS or Uninitialised Data Section and so, as others have suggested, it will be available fot the lifetime of the program.
精彩评论