views:

47

answers:

1

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.

  1. Create Object and create Smart pointer to the object
  2. Call function which has following defination : void Func(void* param) (Note: This function run in different thread context).
  3. 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); ...
...
...
}

+2  A: 

Smart pointers mean that the referenced object gets deleted as soon as the last smart pointer for it is destructed, so what's happening in your code is as expected. You would need to release the pointer from your smart pointer instance, transferring ownership to Func.

Steven Sudit
How do you transfer ownership to function when function has prototype void* as parameter.
Invincible
Depends on the specific type of smart pointer, but there's usually a function named `release` that not only returns a pointer but ensures that the instance no longer deletes it as part of the destructor. You then take this unowned return value and pass it as the parameter to the void* function.
Steven Sudit