c++11 - Why does the C++ standard not prohibit such a dreadful usage? -


the source code simple , self-evident. question included in comment.

#include <iostream> #include <functional>  using namespace std; using namespace std::tr1;  struct {     a()     {         cout << "a::ctor" << endl;     }      ~a()     {         cout << "a::dtor" << endl;     }      void foo()     {} };  int main() {     a;     /*     performance penalty!!!      following line implicitly call a::dtor 6 times!!! (vc++ 2010)         */     bind(&a::foo, a)();        /*     following line doesn't call a::dtor.      obvious that: when binding member function, passing pointer first      argument (almost) best way.       now, problem is:       why c++ standard not prohibit bind(&someclass::somememberfunc, arg1, ...)      taking arg1 value? if so, above bind(&a::foo, a)(); wouldn't     compiled, want.     */     bind(&a::foo, &a)();       return 0; } 

first of all, there third alternative code :

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

now, why parameters taken copy default ? presume, it's wild guess, considered preferable bind default behavior independent of parameters lifetime : result of bind functor of invocation delayed long after parameters destruction.

would expect following code yield ub by default ?

void foo(int i) { /* ... */ }  int main() {     std::function<void ()> f;      {         int = 0;         f = std::bind(foo, i);     }      f(); // boom ? } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -