原始指针和 shared_ptr 之间的 C++ 接口 [英] C++ interface between raw pointers and shared_ptr

查看:40
本文介绍了原始指针和 shared_ptr 之间的 C++ 接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码始终使用原始指针.

I have code that uses raw pointers throughout.

它需要调用一个将原始指针带入shared_ptr的方法.这个方法不受我控制,属于外部api.我不能只是将指针传递给 shared_ptr 因为它什么时候会被删除当 shared_ptr 超出方法的作用域时(当方法返回时).

It needs to call a method that takes the raw pointer into a shared_ptr. This method is not under my control, belonging to an external api. I cannot just pass the pointer to the shared_ptr because when it will be deleted when the shared_ptr goes out of scope in the method (when the method returns).

除了在内部代码中将原始指针设为 shared_ptr 之外,我还有其他选择吗?

Do I have any option other than making my raw pointer a shared_ptr in my internal code?

推荐答案

这听起来有些不寻常,而且可能非常危险,但是您可以在构造 shared_ptr 时使用无操作删除器来实现这一点:

This sounds somewhat unusual and potentially quite dangerous, but you can accomplish this by using a no-op deleter when constructing the shared_ptr:

struct no_op_delete
{
    void operator()(void*) { }
};

int* p = 0; // your pointer
std::shared_ptr<int> sp(p, no_op_delete());

sp 和它的所有副本都被销毁时,将调用 no_op_delete 来清理持有的指针.因为它什么都不做,所以你会得到你需要的行为.

When sp and all copies that were made of it have been destroyed, no_op_delete will be invoked to clean up the held pointer. Since it does nothing, you get the behavior you need.

这篇关于原始指针和 shared_ptr 之间的 C++ 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆