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

まず、コードの 3 番目の代替手段があります。

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 に答える