将智能指针传递给函数(接受 void*)而不调用指针对象的析构函数
我有自己的智能指针实现,它使用引用计数作为所有权机制(注意:我已经测试过它并且没有错误)。
以下是我的代码流程。
- 创建对象并创建指向该对象的智能指针
- 调用函数,该函数具有以下定义:
void Func(void* param)
(注意:该函数在不同的线程上下文中运行)。 但是,当 Func 被调用时出现问题,发生以下情况
- 在参数求值中:它使用复制构造函数创建另一个智能指针
- 两个智能指针都有相同的指针对象,且指针对象的引用计数为 2。
- 在函数被调用之前,第二个智能指针被释放并且引用计数变为 1
- 现在,主线程也消失了,Func 线程正在运行
- 当主线程终止时,它会销毁指针,因为引用计数为 0。
- 因此,Func 出现分段错误!!!
请告诉我,这样做有什么技巧吗? (解决办法也可以。)
谢谢
这是上述事情的示例代码。
(AutoRef
是实现了引用计数的智能指针)。
主线程
AutoRef<MyClass> system(new MyClass);
CreateThread(..., Func, &AutoRef<MyClass>(system)); // In param evaluation step 3 happens
其他线程
// Function code
//
void Func(void* param)
{
// Following line does not invoke copy constructor
// (which is fine as per usage of reinterprete_cast)
AutoRef<MyClass>* system = reinterpret_cast<AutoRef<MyClass>*>(param);
...
...
...
}
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 reference counting implemented).
Main Thread
AutoRef<MyClass> system(new MyClass);
CreateThread(..., Func, &AutoRef<MyClass>(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<MyClass>* system = reinterpret_cast<AutoRef<MyClass>*>(param);
...
...
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
智能指针意味着一旦引用的对象的最后一个智能指针被破坏,它就会被删除,因此代码中发生的情况是预期的。您需要从智能指针实例中释放指针,将所有权转移给 Func。
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.