简体   繁体   English

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

[英]C# delegate equivalent when C++ using smart pointers

I am mainly a .NET programmer working on a C++ project and am trying to determine the equivalent way to handle delegates that use the Action and Function template types. 我主要是一个从事C ++项目的.NET程序员,我正在尝试确定处理使用Action和Function模板类型的委托的等效方法。 I use the delegates both as events and callbacks within the .NET code. 我在.NET代码中使用委托作为事件和回调。 My C++ project uses smart pointers and the same delegate design patterns as a C# program would. 我的C ++项目使用智能指针和与C#程序相同的委托设计模式。 What is the best way to handle this situation? 处理这种情况的最佳方法是什么? It is not clear to me how to pass and maintain a function pointer that also keeps track of the smart pointer and potentially the deletion of the underlying object since the event container uses a weak reference. 我不清楚如何传递和维护一个函数指针,该函数指针也跟踪智能指针并可能删除底层对象,因为事件容器使用弱引用。 The library needs to be multi-platform so using CLR is unfortunately not an option. 该库需要是多平台的,因此不幸的是,使用CLR是一种选择。

What you are looking for is a method pointer bound to an existing object, that's it ? 你在寻找的是一个绑定到现有对象的方法指针,就是这样吗?

The you should have a look for boost::bind . 你应该看看boost :: bind If your environment supports it, you can also use std::tr1::bind or even std::bind if it supports C++11. 如果你的环境支持它,你也可以使用std::tr1::bind甚至std::bind如果它支持C ++ 11。

The example which illustrates what you want is : 说明你想要的例子是:

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, x, _1) stores a copy of x. bind(&X :: f,x,_1)存储x的副本。 bind(&X::f, p, _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(). bind(&X :: f,p,_1)存储p的副本,并且由于p是boost :: shared_ptr,函数对象保留对其X实例的引用,即使p超出范围或者重置()。

For the differences between boost::bind , std::tr1::bind and std::bind , I let you see this other question on SO. 对于boost::bindstd::tr1::bindstd::bind之间的区别,我让你在SO上看到另一个问题。

Take a look at: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible 看看: http//www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

It will also explain why delegates in C++ are a little tricky. 它还将解释为什么C ++中的委托有点棘手。 This library was recommend in a game development book i read (So i'm assuming its very fast). 这个库在我读过的游戏开发书中被推荐(所以我假设它非常快)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM