std::function & Functor(用 Functor 构造std::function时的注意点)
来源:互联网 发布:淘宝拍卖业务管理规范 编辑:程序博客网 时间:2024/05/17 23:31
std::function 可以保存一切可调用的对象( Functor, lamda,bind对象)
std::funciton 可以复制该对象然后绑定复制后的对象的operator()——传值,也可以直接绑定该对象的operator() ——传引用。
std::bind 同样可以复制该对象,然后绑定复制后的对象的某个函数,也可以直接绑定到该对象上。 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 <functional>#include <memory>#include <iostream>int main(){ Functor f; // 这里会调用的是 Functor 的复制构造函数,如果不能复制则不能编译通过。 // 调用 a 将调用复制构造后的新对象的 operator() std::function<int(int, int)> a = f; // 如果 Functor不能够被复制,或者Functor中有成员变量不能够被复制(即默认复制构造失败),则不能够直接用Functor对象来构造 std::function 对象 // 不过下面这样是可以的(不会触发Functor任何构造函数), 只不过要确保在b的生存周期内f一直有效。 // 调用 b 将调用原对象 f 的 operator() std::function<int(int, int)> b = std::ref(f); // 另外,如果Functor提供了 move 构造函数,则下面会调用Functor 的 move 构造函数, 如果不能被move则会被copy构造(因此,复制构造函数也必须显示写出,否则编译不通过) std::function<int(int, int)> c = Functor(); // 这样可以,只会调用Functor的构造函数,不会触发复制构造或move构造, good! std::function<int(int, int)> d = std::bind(&Functor::operator(), std::make_shared<Functor>(), 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
0 0
- std::function & Functor(用 Functor 构造std::function时的注意点)
- functor(function object)
- function object (functor) (1)
- Function 与 Functor 区别
- function object (functor) (3) : Closure
- 仿函数(functor function objects)
- std::function的用法
- std::function的使用
- C++ Review: Function pointer & Function object(functor)
- STD::FUNCTION
- std::function
- std::function
- std::function
- std::function
- std::function
- std::function
- std::function
- std::function
- Android Studio上方便使用butterknife注解框架的偷懒插件Android Butterknife Zelezny
- andrAndroid 权限
- beta分布 and Dirichlet分布
- 1016 Phone Bills
- html meta标签
- std::function & Functor(用 Functor 构造std::function时的注意点)
- pthread_mutex_lock
- VC++2010工程中加入SplashScreen
- struts2日期转换在Win10上失败问题的分析和解决
- eclipse里显示出来context.xml
- sourcetree ssh key生成
- 盘点 8 款好用的开源商城系统
- hdu 1068 Girls and Boys
- ALGO-81动态数组使用普通试题