c 11 – 为什么C标准不禁止这种可怕的使用?
发布时间:2020-12-16 09:31:06 所属栏目:百科 来源:网络整理
导读:源代码非常简单且不言而喻.问题包含在评论中. #include iostream#include functionalusing 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
源代码非常简单且不言而喻.问题包含在评论中.
#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; } 解决方法
首先,您的代码有第三种替代方案:
bind(&A::foo,std::ref(a))(); 现在,为什么默认情况下复制采用参数?我认为,但这只是一个疯狂的猜测,认为绑定默认行为与参数生存期无关是优选的:绑定的结果是一个仿函数,其参数销毁后可能会延迟调用. 您是否希望以下代码默认产生UB? void foo(int i) { /* ... */ } int main() { std::function<void ()> f; { int i = 0; f = std::bind(foo,i); } f(); // Boom ? } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |