为什么C ++标准不禁止这种可怕的使用?

时间:2010-12-01 09:09:15

标签: c++11 bind pass-by-value

源代码非常简单且不言自明。问题包含在评论中。

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

2 个答案:

答案 0 :(得分: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 ?
}

答案 1 :(得分:0)

C ++的任务不是让编写慢速代码变得不可能,甚至更难。它只是要求你明确要求花里胡哨。