成员函数指针——只有一个地址?
http://www.codeproject.com/KB/cpp/fastdelegate2.aspx
在上面文章的介绍的第二段中,它说:“这是由于存储成员函数和对其进行成员函数调用的绑定对象需要昂贵的堆内存分配。” ..我不明白这个?它实际上必须复制并存储对象和成员函数吗?它不是只存储成员函数的地址吗?
http://www.codeproject.com/KB/cpp/fastdelegate2.aspx
In the second paragraf of the introduction in the above article it says: "This is due to the expensive heap memory allocation that is required to store the member function and the bound object on which member function call is made." .. I dont get this? Does it actualy have to copy and store the object and the member function? Doesn't it only store the address of the member function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Boost.Function 比原始函数指针更通用、更强大:它们可以存储任何可使用特定签名调用的内容。然而,这种灵活性会带来存储和运行时间方面的成本。
Boost.Function 的杂项注释部分文档对此进行了更多讨论,但总结一下:
话虽如此,我已经广泛使用了 Boost.Function,并且从未遇到过在分析时实际显示其存储或运行时成本的情况,因此这是否重要将取决于您的实际使用情况。
Boost.Function is more general and powerful than raw function pointers: they can store anything that is callable with a particular signature. However, there is a cost in storage and run-time associated with that flexibility.
The Miscellaneous Notes section of the Boost.Function documentation talks a bit more about this, but to summarize:
Having said all that, I've used Boost.Function extensively and never had a situation where its storage or run-time costs actually showed up when profiling, so whether any of this is important or not will depend on your actual usage.
不,您不能仅使用指向方法的指针来调用成员函数。原因是因为方法是在上下文 (
this
)(调用该方法的对象)内调用的。如果您只有成员函数指针,您将无法知道该方法应该应用于哪个对象。但是,如果成员函数是静态
,则它不具有上下文,因为可以在不实例化对象的情况下调用静态成员函数。因此,要调用成员函数,您需要一个指向该函数的指针,加上一些对定义将在其中调用成员函数的上下文的对象的引用。
这能回答你的问题吗?
No, you can't call a member function with only the pointer to the method. The reason is because methods are called within a context (
this
), the object on which the method is called. If you only have the member function pointer you can't know to which object the method should be applied. However, if the member function isstatic
, then it does NOT have a context, because static member functions can be called without instantiating an object.So to call a member function you need a pointer to the function, PLUS some reference to an object defining the context in which the call to member function will take place.
Does this answer your question?