Why doesn't the C ++ standard prohibit such terrible use?

The source code is very simple and self-evident. The question is included in the comment.

#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;
}
+3
source share
2 answers

First of all, there is a third option for your code:

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

Now, why are the options made by the default copy? I suppose, but this is just a wild hunch that it bind’s preferable for default behavior to be independent of the parameter lifetime: the binding result is a functor whose action can be delayed long before the parameters are destroyed.

Do you expect from the following code you get the default UB?

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

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

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

    f(); // Boom ?
}
+7
source

++ , . , .

0

Source: https://habr.com/ru/post/1777871/


All Articles