【发布时间】:2011-05-18 09:18:20
【问题描述】:
源代码非常简单,不言而喻。该问题包含在评论中。
#include <iostream>
#include <functional>
using namespace std;
using namespace std::tr1;
struct A
{
A()
{
cout << "A::ctor" << endl;
}
~A()
{
cout << "A::dtor" << endl;
}
void foo()
{}
};
int main()
{
A a;
/*
Performance penalty!!!
The following line will implicitly call A::dtor SIX times!!! (VC++ 2010)
*/
bind(&A::foo, a)();
/*
The following line doesn't call A::dtor.
It is obvious that: when binding a member function, passing a pointer as its first
argument is (almost) always the best way.
Now, the problem is:
Why does the C++ standard not prohibit bind(&SomeClass::SomeMemberFunc, arg1, ...)
from taking arg1 by value? If so, the above bind(&A::foo, a)(); wouldn't be
compiled, which is just we want.
*/
bind(&A::foo, &a)();
return 0;
}
【问题讨论】:
-
记住还有第三种选择:
bind(&A::foo, std::ref(a))(); -
@icecrime:我知道。但我只是想知道为什么 C++ 标准没有明确禁止这种可怕而无用的用法?
-
从实现的角度来看,有几个重载的绑定函数,其中一个通过值获取它的第一个参数。如果实现不提供这样的重载功能。那么目标就很容易实现了。
标签: c++11 bind pass-by-value