क्यों सी ++ 11 में std::bind
के साथ एक साथ उपयोग करने के लिए कोई std::protect
है?कोई std :: सुरक्षा क्यों नहीं है?
Boost.Bind एक boost::protect
सहायक है कि इसके तर्क लपेटता ताकि boost::bind
को नहीं पहचानता है और यह मूल्यांकन प्रदान करता है। std::[c]ref
एक अच्छा पर्याप्त प्रतिस्थापन, समय की सबसे हो सिवाय इसके कि यह एक rvalue तर्क के रूप में नहीं ले जाएगा होगा।
एक ठोस उदाहरण के लिए, निम्नलिखित कृत्रिम स्थिति पर विचार:
#include <type_traits>
#include <functional>
int add(int a, int b)
{ return a + b; }
struct invoke_with_42
{
template <typename FunObj>
auto operator()(FunObj&& fun_obj) const -> decltype((fun_obj(42)))
{ return fun_obj(42); }
};
int main()
{
//// Nested bind expression evaluated
//auto bind_expr =
// std::bind<int>(invoke_with_42{}
// , std::bind(&add, 1, std::placeholders::_1));
//// Compilation error, cref does not take rvalues
//auto bind_expr =
// std::bind<int>(invoke_with_42{}
// , std::cref(std::bind(&add, 1, std::placeholders::_1)));
//// Ok, inner_bind_expr must be kept alive
auto inner_bind_expr =
std::bind(&add, 1, std::placeholders::_1);
auto outer_bind_expr =
std::bind<int>(invoke_with_42{}, std::cref(inner_bind_expr));
//// Ok, with protect
//auto bind_expr =
// std::bind<int>(invoke_with_42{}
// , std::protect(std::bind(&add, 1, std::placeholders::_1)));
}
यह प्रस्तावित किया गया था? –
एक 'एक' rvalue' पर cref' शायद विनाशकारी होगा - temporaries जीवन थोड़ा इसके चारों ओर जब तक रखने के रूप में 'bind' आपत्ति यह करने के लिए पारित किया जा रहा है (या जो भी) के लिए होगा। – Yakk
आप 'bind' परिणाम को 'std :: function' पर असाइन करके" सुरक्षित "भी कर सकते हैं, हालांकि यह रनटाइम ओवरहेड जोड़ता है। – Potatoswatter