3

源代码非常简单,不言而喻。问题包含在评论中。

#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;
}
4

2 回答 2

7

首先,您的代码还有第三种选择:

bind(&A::foo, std::ref(a))(); 

现在,为什么默认情况下通过复制获取参数?我推测,但这只是一个疯狂的猜测,bind默认行为与参数生命周期无关被认为是可取的:绑定的结果是一个函子,其调用可能在参数销毁后很长时间被延迟。

您是否希望以下代码默认产生 UB ?

void foo(int i) { /* ... */ }

int main()
{
    std::function<void ()> f;

    {
        int i = 0;
        f = std::bind(foo, i);
    }

    f(); // Boom ?
}
于 2010-12-01T09:24:55.850 回答
0

C++ 的使命不是让编写慢代码变得不可能,甚至更难。这只是要求您明确要求花里胡哨。

于 2010-12-01T09:29:23.407 回答