您的位置:首页 > 其它

boost::bind会返回一个函数对象,它内部保存了数据的拷贝

2016-10-03 22:54 381 查看
boost::bind会返回一个函数对象,它内部保存了数据的拷贝。

#include <string>
#include <iostream>
#include <thread>
#include <boost/thread.hpp>
#include <boost/asio.hpp>

std::string LocalTime()
{
time_t tt = std::chrono::system_clock::to_time_t
(std::chrono::system_clock::now());
struct tm* ptm = localtime(&tt);
std::string buff(20, '\0');//[19个长度]+[结尾符'\0']=[20个长度],
std::sprintf(const_cast<char*>(buff.c_str()), "%04d-%02d-%02dT%02d:%02d:%02d",
(int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday,
(int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec);
buff.resize(19);
return buff;
}

void TestFun(const std::string& msg)
{
if (true)
{
std::cout << "other, " << LocalTime() << ", msg=" << msg << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(6));
if (true)
{
std::cout << "other, " << LocalTime() << ", msg=" << msg << std::endl;
}
}

int main()
{
//《Boost程序库完全开发指南 第3版》P454: 绑定完成后,bind会返回一个函数对象,它内部保存了f的拷贝,...
boost::thread_group thgp;
boost::asio::io_service io;
boost::asio::io_service::work wk(io);
boost::system::error_code ec;
thgp.create_thread(boost::bind(&boost::asio::io_service::run, boost::ref(io), ec));

if (true)
{
std::cout << "====== not use reference ======" << std::endl;
std::string str;
if (true)
{
str = "before modify";
std::cout << "main , " << LocalTime() << ", str=" << str << std::endl;
}
//参数str没有传递引用,此时bind会保存str的拷贝,
io.post(boost::bind(TestFun,            str ));
//io.post(boost::bind(TestFun, boost::ref(str)));
std::this_thread::sleep_for(std::chrono::seconds(3));
if (true)
{
str = "after modify";
std::cout << "main , " << LocalTime() << ", str=" << str << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(15));
}
if (true)
{
std::cout << "====== use reference ======" << std::endl;
std::string str;
if (true)
{
str = "before modify";
std::cout << "main , " << LocalTime() << ", str=" << str << std::endl;
}
//参数str传递了引用,此时bind会保存str的引用,如果str被改变了,那么函数对象里面的str自然被改变了,
//io.post(boost::bind(TestFun,            str ));
io.post(boost::bind(TestFun, boost::ref(str)));
std::this_thread::sleep_for(std::chrono::seconds(3));
if (true)
{
str = "after modify";
std::cout << "main , " << LocalTime() << ", str=" << str << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(15));
}
return 0;
}

其结果如下所示:

====== not use reference ======
main , 2016-10-03T22:54:46, str=before modify
other, 2016-10-03T22:54:46, msg=before modify
main , 2016-10-03T22:54:49, str=after modify
other, 2016-10-03T22:54:52, msg=before modify
====== use reference ======
main , 2016-10-03T22:55:04, str=before modify
other, 2016-10-03T22:55:04, msg=before modify
main , 2016-10-03T22:55:07, str=after modify
other, 2016-10-03T22:55:10, msg=after modify
完。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐