Hello:
I have my own implementation of smart pointer which uses reference counting as ownership mechanism (Note: I have tested it and it has no bugs).
Following is my code flow.
- Create Object and create Smart pointer to the object
- Call function which has following defination : void Func(void* param) (Note: This function run in different thread context).
But, problem arises when Func get called, following thing happens
- In parameter evaluation: It creates another smart pointer using copy constructor
- Both smart pointer has same pointee and ref count of pointee is 2.
- Before function get invoked second smart pointer get released and ref count becomes 1
- Now, main thread also dies out and Func thread is running
- When, main thread dies out it destroys the pointee because ref count is 0.
- Hence, Func get segmentation fault!!!
Please let me know, Is there any trick for doing this? (work around will work too.)
Thanks
Here is sample code for above thing.
(AutoRef is smart pointer with refernece counting implemented).
Main Thread
AutoRef system(new MyClass);
CreateThread(..., Func, &AutoRef(system)); // In param evaluation step 3 happens
Other thread
// Function code
//
void Func(void* param)
{
// Following line does not invoke copy constructor
// (which is fine as per usage of reinterprete_cast)
AutoRef* system = reinterpret_cast*>(param);
...
...
...
}