微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当C使用智能指针时,C#委托等效

我主要是一个从事C项目的.NET程序员,我正在尝试确定处理使用Action和Function模板类型的委托的等效方法.我在.NET代码中使用委托作为事件和回调.我的C项目使用智能指针和与C#程序相同的委托设计模式.处理这种情况的最佳方法是什么?我不清楚如何传递和维护一个函数指针,该函数指针也跟踪智能指针并可能删除底层对象,因为事件容器使用弱引用.该库需要是多平台的,因此不幸的是,使用CLR是一种选择.

解决方法

你在寻找的是一个绑定到现有对象的方法指针,就是这样吗?

您应该查看boost::bind.如果您的环境支持它,您还可以使用std :: tr1 :: bind或甚至std :: bind(如果它支持C 11).

说明你想要的例子是:

struct X
{
    bool f(int a);
};
X x;
shared_ptr<X> p(new X);
int i = 5;

bind(&X::f,ref(x),_1)(i);     // x.f(i)
bind(&X::f,&x,_1)(i);         //(&x)->f(i)
bind(&X::f,x,_1)(i);          // (internal copy of x).f(i)
bind(&X::f,p,_1)(i);          // (internal copy of p)->f(i)

The last two examples are interesting in that they produce “self-contained” function objects. bind(&X::f,_1) stores a copy of x. bind(&X::f,_1) stores a copy of p,and since p is a boost::shared_ptr,the function object retains a reference to its instance of X and will remain valid even when p goes out of scope or is reset().

对于boost :: bind,std :: tr1 :: bind和std :: bind之间的区别,我让你看到this other question on SO.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐