std::function&Functor(Functorでstd::functionを構築する際の注意点)

1951 ワード

std::functionは呼び出し可能なすべてのオブジェクト(Functor,lamda,bindオブジェクト)を保存できます.
std::funcitonは、オブジェクトをコピーし、コピーしたオブジェクトのoperator()をバインドしたり、オブジェクトのoperator()を直接バインドしたりすることができます.std::bindパスパラメータも、std::refを使用して参照する場合にデフォルトでコピーされます.std::bind uses value semantics by default, but you can use std::ref
Functor:
class Functor
{
public:
	Functor()=default;  //   ,   c++11 ,             ( ,    ),                 (       ),      !
	int operator() (int a, int b)
	{
		return a+b;
	}
private:
	Functor(const Functor&);  //     ,for test
}

std::function
#include 
#include 
#include 

int main()
{
	Functor f;
	
	//         Functor        ,             。
	//    a               operator()
	std::function a = f;
	
	//    Functor      ,  Functor            (         ),       Functor      std::function   
	//           (    Functor      ),        b      f    。
	//    b        f   operator()
	std::function b = std::ref(f);

    //    bind      
    std::function c = std::bind( &Functor ::operator(), &f );
	
	//   ,  Functor    move     ,      Functor   move     ,      move   copy  (  ,             ,       )
	std::function d = Functor();
	
	//     ,    Functor     ,         move  , good!
	std::function e = std::bind(&Functor::operator(), std::make_shared(), std::placeholders::_1, std::placeholders::_2);

	return 0;
}

したがって、Functorをstd::functionに保存するときは、クラスメンバーのコピー可能性(およびmove)を考慮するか、最後のmake_を使用します.shared+bindの方法です.そうしないと、コンパイルは問題に合格しません.
see link: http://blog.csdn.net/GW569453350game/article/details/46649517 https://gcc.gnu.org/onlinedocs/libstdc++/libstdc+±api-4.6/a00481.html http://stackoverflow.com/questions/27953336/constructing-stdfunction-target-in-place