c++ - 为什么委托(delegate)或闭包通常被称为 true "object-oriented function pointers"?

标签 c++ oop delegates closures function-pointers

例如,考虑 C#

Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

来源: http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx

现在只谈论 C++,真正的区别是什么?面向对象的前景缺少什么?

也来自其他来源

Most C++ programmers have never used member function pointers, and with good reason. They have their own bizarre syntax (the ->* and .* operators, for example), it's hard to find accurate information about them, and most of the things you can do with them could be done better in some other way. This is a bit scandalous: it's actually easier for a compiler writer to implement proper delegates than it is to implement member function pointers!

来源: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

我发现很多 C++ 程序都使用 ->* 语法,我不觉得这很奇怪或奇怪;我不明白委托(delegate)的这种潜力和对指针的攻击。<​​/p>

最佳答案

成员指针和真正的闭包之间的区别在于闭包包含函数相关联的状态。两者密不可分。

成员指针只是函数。为了调用成员指针,您必须提供状态。

这是函数指针和仿函数的区别。函数对象保存要调用的函数(作为 operator() 的重载),但它可以有成员。这些成员可以是私有(private)的,从而提供封装。函数对象是 C++ 规则的对象,因此它具有明确的生命周期。它根据 C++ 规则构造和析构。

函数指针没有生命周期;它总是存在的(除非它是 NULL)。它没有要封装的状态。

因此,它不是闭包,因为它不能关闭任何东西。

这就是 C++11 lambda 被实现为显式对象的原因。这样,他们就可以结束一切。它们具有封装状态。

关于c++ - 为什么委托(delegate)或闭包通常被称为 true "object-oriented function pointers"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11908184/

相关文章:

ios - 响应者链但不是委托(delegate)属性将值从容器传递回 View Controller

c++ - 将 C 编译为 C++ 链接器错误(lua 和 oolua)

c++ - 插入功能点到新数据

oop - DDD 是浪费时间吗?

javascript - 如何将原型(prototype)函数添加到初始化函数中的事件监听器?

c# - 以数据为中心的应用程序的设计模式

ios - 单点触控/iOS : which place is the best one to unsubscribe the delegate

swift - 在初始化之前设置 CustomView 委托(delegate)

c++ - C++中partition()和remove()函数的区别

c++ - 带有 if 语句的嵌套 for 循环的时间复杂度