码迷,mamicode.com
首页 > 编程语言 > 详细

向线程中的函数传入参数的注意事项

时间:2015-01-28 19:18:42      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

1. 当函数的形参类型为 string, 而传入的参数类型为 char[] 时, 需要在线程函数中转型, 如此可以避免空悬指针。如:

void f(int, std::string const&);

void oops(int some_parm)
{
    char buffer[100];
    sprintf(buffer, "%i", some_parm);
    //std::thread(f, 3, buffer)      //not do this
    std::thread(f, 3, string(buffer)) //instead of    
}

2. 当线程函数的形参为引用时, 不可以直接传入参数, 而应明确转为引用, 如:

void find_by_idx(int&);

void opps_again()
{
    int idx = 6;
    //std::thread t(find_by_idx, idx);        //damn no
    std::thread t(find_by_idx, std::ref(idx)); //damn good
}

3. 成员函数也可以作为线程函数
如:

class X
{
public:
    void do_something(Type parm);
};

X my_x;
std:thread(&X::do_something, my_x; the_parm);

 

向线程中的函数传入参数的注意事项

标签:

原文地址:http://www.cnblogs.com/wuOverflow/p/4256526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!