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

xml*_*lmx 3 bind pass-by-value c++11

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

ice*_*ime 7

首先,您的代码有第三种替代方案:

bind(&A::foo, std::ref(a))(); 
Run Code Online (Sandbox Code Playgroud)

现在,为什么默认情况下复制采用参数?我认为,但这只是一个疯狂的猜测,bind默认行为被认为优于独立于参数的生命周期:绑定的结果是一个函数,其参数销毁后可能会延迟调用.

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

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

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

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

    f(); // Boom ?
}
Run Code Online (Sandbox Code Playgroud)