使用指针和共享指针时,删除时发生访问冲突
我有一个相当大的遗留应用程序,它只使用普通指针。 现在我正在添加一个新模块,尝试使用“更现代的东西”,例如智能指针。
主模块通过通信 DLL 向我的新子模块发送一条消息(使用普通指针)。 在我的新子模块中,我使用共享指针进行消息处理。 当共享指针尝试删除该指针时,我在消息的析构函数中遇到访问冲突,因为 VTable 指针是 0xdddddddd。我已经找到这个问题< /a> ,这表示这是因为指针已经被释放。
在共享指针删除普通指针之前,主模块似乎已经删除了它。
我不想在旧的主模块中使用共享指针(此时将进行大量重构),但是是否有解决方案如何在我的应用程序中使用普通指针和共享指针? 析构函数中通常的 NULL 检查没有帮助。
I have a fairly large legacy application, which uses only normal pointers.
Right now I am adding a new module, trying to use "more modern stuff", e.g. smart pointers.
The main module sends a message over a communication DLL to my new submodule (with a normal pointer).
In my new submodule I am using shared_pointer for message handling.
When the shared pointer tries to delete the pointer, I get an access violation in the dectructor of the message, because VTable pointer is 0xdddddddd. I have already found this SO question , which says this is because the pointer has already been released.
It seems the main module is already deleting the normal pointer, before shared pointer deletes it.
I don't want to use shared pointers in the old main module (would be very much refactoring at this point), but is there a solution how I can use both normal and shared pointers in my application?
The usual NULL check in the destructor does not help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要确保主模块转移指针的所有权。
即:在发送到您的模块后,它不应该维护任何指向该地址的指针。否则,它可能会释放指针,使模块成为悬空指针。
因此,如果主模块维护对指针的引用,那么仅对您的模块使用 shard_ptr 是没有意义的。在这种情况下,您还需要在主模块中使用
shared_ptr
。另外,您需要确保对
shared_ptr::deleter()
中的指针使用适当的内存释放例程。可能出现的情况是,用于指针的分配和释放例程不匹配。
You need to make sure that the main module transfers the ownership of the pointer.
i.e: It should not maintain any pointer to that address after it is sent to your module. Otherwise it may deallocate the pointer leaving your module with a dangling pointer.
So, If the main module maintains references to the pointer then using
shard_ptr
just for your module doesn't make sense. In that case you will need to useshared_ptr
in the main module too.Also, you need to make sure that you are using appropriate memory deallocation routine for the pointer in the
shared_ptr::deleter()
.It might be the case that there is mis-match in allocation and deallocation routines being used for the pointer.