std::call_once()与指针函数,向函数传递函数

1.std::call_once(): 指定函数只会被执行一次

std::call_once()该函数的第二个参数是一个函数名 fun();
std::call_once()的功能是保证函数 fun() 只会被调用一次(无论是单线程中多次被调用,或者在多线程中被多次调用);
std::call_once()具备互斥量这种能力,而且在效率上,比互斥量的消耗的资源更少;
std::call_once()需要与一个标记结合使用,这个标记std::once_flag;std::once_flag其实是一个结构,std::call_once()就是通过这个标记来决定对应fun()函数对否执行,调用std::call_once()成功后,std::call_once()就会把这个标记设置为一种已调用的状态,后续再次调用std::call_once(),只要once_flag被设置为了“已调用”状态,那么对应的函数fun()就不会再被执行;

#include<iostream>
#include<mutex>				//for  std::call_once();
using namespace std;
std::once_flag gflag;		//标记
void func(int x)
{
    cout<<x<<endl;
}

int main()
{
    int num=100;
    std::call_once(gflag,func,std::ref(num));   //引用传递
    std::call_once(gflag,func,num);             //值传递
    return 0;
}
//自定义call_once函数;
#include<iostream>
#include<mutex>				//for  std::call_once();
using namespace std;
bool flag=true;

void callone(bool *flag,void (*fun)()){
    if(*flag)
    {
       (*fun)();
       *flag=false;
    }
    return ;
}
void testprint()
{
    cout<<"test call_once"<<endl;
}

int main()
{
    callone(&flag,testprint);
    callone(&flag,testprint);
    
    return 0;
}

2.指针函数

指针函数:由于函数名是一个函数的入口地址,所以可以过函数名执行这个函数;
指针函数,就是通过函数地址,找到函数入口,从而执行函数;

#include <iostream>
using namespace std;
void funPtr(int x){
    cout<<"this is a ptr func"<<"and the num is "<<x<<endl;
}
int main()
{
    void (*ptr)(int);//!指针函数;由于函数名是一个函数的入口地址,所以可以过函数名执行这个函数;
                        //!指针函数,就是通过函数地址,找到函数入口,从而执行函数;
    int num=100;
    ptr=funPtr;     //将函数地址赋予ptr;

    (*ptr)(num);    //执行函数
    return 0;
}

2.1 函数作形参

在有些情况下需要将函数作为参数,提供给某个函数进行调用;

void fun(int x,int y)   //!带带参数,不带返回值
{
    cout<<" x+y is "<<x+y<<endl;
}

int fun2(string str){   //!带参数 与 返回值;
    cout<<str<<endl;
    return str.size();
}

//! 向一个函数传递一个函数时,形参的必须要包含传递函数的参数值的类型-->(void (*ptrFun)(int,int))。
void callOtherFunc(void (*ptrFun)(int,int),int arg1,int arg2){
    (*ptrFun)(arg1,arg2);
}

//! 必须要包含传递函数的参数值的类型-->(int (*ptrFun)(string))。
int  callOtherFunc2(int (*ptrFun)(string),string arg){
    int re=(*ptrFun)(arg);
    return re;
}
int main()
{
    int arg1=10,arg2=50;
    callOtherFunc(fun,arg1,arg2);

    int re=callOtherFunc2(fun2,"this is a test");
    cout<<re<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值