c++ - Swapping std::functions with user-implemented swaps -
i have created functor defines own swap function. simplicity assume functor's operator signature int (int). if initialize 2 std::function functor, std_func1 , std_func2, swapping them call user-implemented swap function of functor or not? in advance.
here have tried:
#include <iostream> #include <vector> #include <boost/function.hpp> using namespace std; class myclass { public: myclass(int n):data_(n,0){} void swap(myclass& rhs) { using std::swap; std::cout << "swapping myclass" << '\n'; data_.swap(rhs.data_); } private: vector<int> data_; }; struct square { square(int n):b(n){} int operator()(int x) { return x*x; } myclass b; void swap(square& rhs) { using std::swap; std::cout << "swapping square" << '\n'; b.swap(rhs.b); } }; void swap(myclass& a, myclass& b) { a.swap(b); } void swap(square& a, square& b) { a.swap(b); } using myfunction = std::function<int (int)>; int main () { myfunction myf1(square(10)); myfunction myf2(square(20)); myf1.swap(myf2); /* not use user-implemented swap functions */ return 0; }
std::function::swap(function& other) noexcept
defined as:
effects: interchanges targets of
*this
,other
while unclear whether allows implementation call swap
on targets, natural assume not, since existence of swap
member in target erased once target put std::function
. means take significant effort (and runtime inefficiency) implementation know , call through user-defined swap
in situations existed (while maintaining backup implementation when user-defined swap
not available).
furthermore, using user-defined swap when available, swapping pointers in other situations, rather inconsistent , confusing.
in particular situation, function marked noexcept
, while square::swap
implementation not, , not legal implementation call (as potentially break noexcept
contract).
Comments
Post a Comment