BOOST学习笔记
1 tool
#pragma once
#include <vector> #include "boost/noncopyable.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/serialization/singleton.hpp" #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
using namespace boost;
using namespace std;
using namespace boost::serialization;
class CNo_copy_class : public noncopyable
{
public:
CNo_copy_class() : a(){}
int a;
}; void no_copy_test()
{
CNo_copy_class c1;
//CNo_copy_class c2(c1);
} vector<int> func()
{
return vector<int>(, );
} void typeof_auto_test()
{
//decltype(20*3.0) x1 = 20*3.0;
BOOST_TYPEOF(*3.0) x2 = *3.0; BOOST_AUTO(&a, new double[]);
BOOST_AUTO(p, make_pair(, "string")); BOOST_AUTO(v ,func()); //注册自定义类型
BOOST_TYPEOF_REGISTER_TYPE(CNo_copy_class)
BOOST_AUTO( pdef, new CNo_copy_class());
cout<< typeid(pdef).name() << endl;
} typedef singleton<CNo_copy_class> origin; void singleton_test()
{
cout << origin::get_const_instance().a << endl;
//origin::get_const_instance().a = 5;
cout << origin::get_mutable_instance().a << endl;
origin::get_mutable_instance().a = ;
cout << origin::get_const_instance().a << endl;
}
2 file
#pragma once
#include "boost/filesystem.hpp" using namespace boost;
using namespace std; void path_string_opt_test()
{
filesystem::path p1;
assert(p1.empty()); filesystem::path p2("c:/user/local/include/xx.js");
cout << p2.string() << endl; if (p2.has_stem()) //xx,文件名,无后缀
{
cout << p2.stem() << endl;
}
if (p2.has_extension()) //.js,文件名后缀
{
cout << p2.extension() << endl;
}
if (p2.has_filename()) //xx.js,文件全名,有后缀
{
cout << p2.filename() << endl;
}
if (p2.has_parent_path()) //c:/user/local/include,除去文件名的路径
{
cout << p2.parent_path() << endl;
} if (p2.has_root_name()) //windows路径为c:
{
cout << p2.root_name() << endl;
}
if (p2.has_root_directory()) //windows路径为/
{
cout << p2.root_directory() << endl;
}
if (p2.has_root_path()) //windows路径为c:/
{
cout << p2.root_path() << endl;
} //修改文件路径
cout << p2.replace_extension("hxx") << endl; //修改扩展名,修改后为c:/user/local/include/xx
cout << p2.replace_extension() << endl; //修改扩展名,修改后为c:/user/local/include/xx
cout << p2.remove_filename() << endl; //移除文件名,修改后为c:/user/local/include
} void GetModulePath()
{
char szPath[MAX_PATH];
GetModuleFileName( NULL, szPath, MAX_PATH );
cout << szPath << endl;
//输出:p:\workspace\proj\test\boost_test\build\src\Debug\BOOST_TEST.exe cout << boost::filesystem::initial_path<filesystem::path>().string() <<endl;
//输出:p:\workspace\proj\test\boost_test\build\src //
cout << boost::filesystem::current_path().string() << endl;
} void directory_test()
{
boost::filesystem::path p1(boost::filesystem::current_path());
p1.append("123\\456");
//循环创建目录
if (!boost::filesystem::exists(p1))
{
boost::filesystem::create_directories(p1);
}
//递归删除最底层目录
if (boost::filesystem::exists(p1))
{
boost::filesystem::remove_all(p1);
}
}
3 container
#pragma once
#include <map>
#include <vector>
#include "boost/array.hpp"
#include "boost/any.hpp"
#include "boost/foreach.hpp" using namespace boost;
using namespace std; void array_test()
{
array<int, > ar = {,};
array<string, > ars = {""};
for (int i=; i<; i++)
{
cout << ars[i] << endl;
}
} void any_test()
{
any a();
int n = any_cast<int>(a); any_cast<int&>(a) = ;
} void foreach_test()
{
int a[] = {, , , , , };
vector<int> vec(a , a + );
BOOST_FOREACH(int x, vec)
{
cout << x << endl;
}
BOOST_REVERSE_FOREACH(int x, vec)
{
cout << x << endl;
}
}
4 smart_ptr
#pragma once
#include<iostream>
#include <vector>
#include "boost/smart_ptr.hpp"
using namespace boost;
using namespace std; //
void scoped_ptr_test()
{
scoped_ptr<int> p(new int);
if (p)
{
*p = ;
cout << *p << endl;
}
p.reset();
} void scoped_array_test()
{
scoped_array<int> p(new int[]);
fill_n(&p[], , );
p[] = p[] + p[];
} void shared_ptr_test()
{
shared_ptr<int> p(new int());
*p = ;
//shared_ptr< vector<int> > mp = make_shared< vector<int> >(100,5); //shardptr可以指定析构函数 } void shared_array_test()
{
shared_array<int> p(new int[]);
shared_array<int> p2 = p;
p[] = ;
assert( p2[] == );
} void weak_ptr_test()
{
shared_ptr<int> sp(new int());
assert(sp.use_count() == ); weak_ptr<int> wp(sp);
assert(wp.use_count() == ); if (!wp.expired())
{
shared_ptr<int> sp2 = wp.lock();
*sp2 = ;
assert(wp.use_count() == );
}
assert(wp.use_count() == );
sp.reset();
assert(wp.expired());
assert(!wp.lock());
}
5 function
#pragma once
#include "boost/utility/result_of.hpp"
#include "boost/any.hpp"
#include "boost/bind.hpp"
#include "boost/function.hpp" using namespace boost;
using namespace std; template<typename T, typename T1>
typename result_of<T(T1)>::type call_func(T t, T1 t1)
{
return t(t1);
} void result_of_test()
{
typedef double (*Func)(double);
Func func = sqrt; result_of<Func(double)>::type x = func(5.0);
cout << typeid(x).name() << endl; any x2 = call_func(func, 5.0);
cout << typeid(boost::any_cast<double>(x2)).name() << endl;
} int f(int a, int b)
{
return a + b;
} int g(int a, int b, int c)
{
return a + b*c;
} void bind_test()
{
cout << bind(f, , )() << endl;
int x = , y = , z = ;
cout << bind(f, _1, )(x) << endl; //使用占位符
cout << bind(g, _3, _2, _2)(x, y, z) << endl; //使用占位符,乱序 //绑定成员函数
class demo
{
public:
int f(int a, int b)
{
cout << a << " "<< b << endl;
return a + b;
}
} a;
demo& b = a;
demo* p = &a;
cout << bind(&demo::f, a, _1, )() << endl;
cout << bind(&demo::f, b, _2, _1)(, ) << endl;
cout << bind(&demo::f, p, _1, _2)(, ) << endl; //算法容器
class point
{
public:
int x,y;
point() : x(), y() {}
void print()
{
cout << x << " " << y << endl;
}
};
std::vector<point> v();
for_each(v.begin(), v.end(), bind(&point::print, _1)); //成员函数_1表示函数指针
} void function_test()
{
boost::function<int(int, int)> func = f;
if (func)
{
cout << func(, ) << endl;
}
func.clear(); boost::function<int(int)> func1 = boost::bind(f, _1, );
if (func1)
{
cout << func1() << endl;
}
}
6 pool
#pragma once
#include <vector>
#include "boost/pool/pool.hpp"
#include "boost/pool/object_pool.hpp"
#include "boost/pool/singleton_pool.hpp"
#include "boost/pool/pool_alloc.hpp"
using namespace boost;
using namespace std; class demo_class
{
public:
int a,b,c;
demo_class(int x = ,int y=, int z=):a(x), b(y), c(z)
{
}
};
typedef singleton_pool<demo_class , sizeof(demo_class)> spl; void pool_test()
{
pool<> pl(sizeof(int));
int* p = static_cast<int*>(pl.ordered_malloc());
assert(pl.is_from(p)); pl.ordered_free(p); for (int i=; i<; i++)
{
pl.ordered_malloc();
}
} void object_pool_test()
{
object_pool<demo_class> pl;
demo_class *p = pl.malloc();
assert(pl.is_from(p)); assert(p->a != || p->b != || p->c != ); p =pl.construct(, , );
assert(p->a == ); object_pool<std::string> pls;
for (int i=; i< ;i++)
{
std::string *ps = pls.construct("hello");
cout<< ps->c_str() << endl;
}
} void singleton_pool_test()
{
demo_class* p = (demo_class*)spl::malloc();
assert(spl::is_from(p));
spl::release_memory();
} void pool_alloc_test()
{
std::vector<int, pool_allocator<int> > v;
v.push_back();
}
7 thread
#pragma once
#include <stack>
#include <vector>
#include "boost/thread.hpp"
#include "boost/foreach.hpp" using namespace boost;
using namespace std; boost::mutex io_mu_1;
void time_test()
{
this_thread::sleep_for(chrono::seconds()); this_thread::sleep_until(chrono::system_clock::now() + chrono::seconds());
} void to_interrupt(int& x, const string& str)
try
{
for (int i=; i<; i++)
{
boost::mutex::scoped_lock(io_mu_1);
cout << str << ++x << std::endl;
//this_thread::sleep_for(chrono::seconds(1));
{
//自动中断点 }
this_thread::interruption_point();
}
}
catch(...)
{
cout << "thread_interrupted" << std::endl;
}; void thread_test()
{
int x = ;
boost::thread t(to_interrupt, boost::ref(x), "hello");
this_thread::sleep_for(chrono::seconds()); t.interrupt();
assert(t.interruption_requested()); t.join();
} //测试条件变量
class buffer
{
public:
buffer(int n) : un_read(),capacity(n)
{
}
void put(int x)
{
{
boost::mutex::scoped_lock lock(mu);
while (if_full())
{
{
//boost::mutex::scoped_lock lock2(io_mu_1);
cout<< "full waiting\n";
}
cond_put.wait(mu);
}
}
stk.push(x);
++un_read;
cond_get.notify_one();
}
void get(int* x)
{
{
boost::mutex::scoped_lock lock(mu);
while (is_empty())
{
{
//boost::mutex::scoped_lock lock2(io_mu_1);
cout<< "empty waiting\n";
}
cond_get.wait(mu);
}
}
--un_read;
*x = stk.top();
stk.pop();
cond_put.notify_one();
}
private:
boost::mutex mu;
boost::condition_variable_any cond_put;
boost::condition_variable_any cond_get;
std::stack<int> stk;
int un_read,capacity;
bool if_full()
{
return un_read == capacity;
}
bool is_empty()
{
return un_read == ;
}
} buf(); void producer(int n)
{
for (int i=; i< n; i++)
{
{
//boost::mutex::scoped_lock lock(io_mu_1);
cout << "put " << i << std::endl;
}
buf.put(i);
}
} void consumer(int n)
{
int x;
for (int i=; i< n; i++)
{
buf.get(&x);
//boost::mutex::scoped_lock lock(io_mu_1);
cout << "get " << x << std::endl;
}
} void condition_test()
{
boost::thread t1(producer, );
boost::thread t2(consumer, );
boost::thread t3(consumer, ); t1.join();
t2.join();
t3.join(); boost::this_thread::sleep_for(boost::chrono::seconds());
} //共享互斥量
class rw_data
{
public:
rw_data() : m_x() {}
void write()
{
unique_lock<shared_mutex> ul(rw_mu);
++m_x;
}
void read(int* x)
{
shared_lock<shared_mutex> sl(rw_mu);
*x = m_x;
}
private:
int m_x;
shared_mutex rw_mu;
}; void writer(rw_data& d)
{
for (int i=; i< ; i++)
{
this_thread::sleep_for(chrono::milliseconds());
d.write();
}
} void reader(rw_data& d)
{
int x;
for (int i=; i< ; i++)
{
this_thread::sleep_for(chrono::milliseconds());
d.read(&x);
cout << this_thread::get_id()<< " read: "<<x<<std::endl;
}
} void shared_mutex_test()
{
rw_data d;
boost::thread_group pool;
pool.create_thread(bind(writer, boost::ref(d)));
pool.create_thread(bind(writer, boost::ref(d))); pool.create_thread(bind(reader, boost::ref(d)));
pool.create_thread(bind(reader, boost::ref(d)));
pool.create_thread(bind(reader, boost::ref(d)));
pool.create_thread(bind(reader, boost::ref(d))); pool.join_all();
this_thread::sleep_for(chrono::seconds());
} //future,线程返回执行结果
int fab(int n)
{
if (n == || n == )
{
return ;
}
return fab(n-) + fab(n-);
} void future_test()
{
//单个future
boost::packaged_task<int> pt(bind(fab, ));
boost::BOOST_THREAD_FUTURE<int> f = pt.get_future(); boost::thread(boost::move(pt));
f.wait(); cout << f.get() << endl;
this_thread::sleep_for(chrono::seconds()); //多个future协调,wait for all/any
typedef boost::packaged_task<int> pti_t;
typedef boost::BOOST_THREAD_FUTURE<int> fi_t; boost::array<pti_t, > ap;
boost::array<fi_t, > af; for (int i = ; i<;i++)
{
ap[i] = pti_t(bind(fab, i+ ));
af[i] = ap[i].get_future();
boost::thread(boost::move(ap[i]));
} boost::wait_for_all(af.begin(), af.end());
BOOST_FOREACH(fi_t& f, af)
{
cout << f.get() << endl;
} for (int i = ; i<;i++)
{
boost::thread(boost::move(ap[i]));
} boost::wait_for_any(af.begin(), af.end());
BOOST_FOREACH(fi_t& f, af)
{
if (f.is_ready() && f.has_value())
{
cout << f.get() << endl;
}
} this_thread::sleep_for(chrono::seconds());
} //线程本地存储
boost::thread_specific_ptr<int> pi; //本地线程存储一个int void printing()
{
pi.reset(new int()); ++(*pi);
cout << this_thread::get_id() << " thread, value = " << *pi << endl;
}
void tls_test()
{
(boost::thread(bind(printing)));
(boost::thread(bind(printing))); this_thread::sleep_for(chrono::seconds());
}
8 asio
8.1 server
#pragma once
#include <vector> #include "boost/asio.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/smart_ptr.hpp" using namespace boost;
using namespace boost::asio;
using namespace std; boost::asio::io_service g_ios; //所有的asio都要有个ios //同步定时器
void deadlime_timer_sync_test()
{
boost::asio::deadline_timer t(g_ios, posix_time::seconds());
cout << t.expires_at() << endl; //终止绝对时间
t.wait();
} //异步定时器
//异步定时器回调标准格式
void print(system::error_code x)
{
cout << "deadline time\n";
} void deadlime_timer_async_test()
{
boost::asio::deadline_timer t(g_ios, posix_time::seconds());
cout << t.expires_at() << endl; //终止绝对时间
t.async_wait(print);
cout << "deadline time\n";
g_ios.run();
} //tcp
void tcp_address_test()
{
boost::asio::ip::address addr;
//addr = addr.from_string("ab.12.23.34");
//assert(addr.is_v6());
addr = addr.from_string("127.0.0.1");
assert(addr.is_v4());
cout << addr.to_string() << endl;
ip::tcp::endpoint ep(addr, );
assert(ep.address() == addr);
assert(ep.port() == );
} //服务端
void server_test()
{
ip::tcp::acceptor acceptor(g_ios,
ip::tcp::endpoint(ip::tcp::v4(), )); while ()
{
ip::tcp::socket sock(g_ios);
acceptor.accept(sock); cout << "recv client: " << sock.remote_endpoint().address() << endl;
sock.write_some(boost::asio::buffer(std::string("hello"))); //发送数据
}
} //异步
typedef boost::shared_ptr<ip::tcp::socket> sock_ptr;
class server
{
public:
server() : acceptor(g_ios,
ip::tcp::endpoint(ip::tcp::v4(), ))
{
start();
}
void start()
{
sock_ptr sock(new ip::tcp::socket(g_ios));
acceptor.async_accept(*sock,
bind(&server::accept_handler, this, asio::placeholders::error, sock));
}
void accept_handler(const system::error_code& ec, sock_ptr sock)
{
if (ec)
{
return;
}
cout << sock->remote_endpoint().address() << endl;
sock->async_write_some(boost::asio::buffer(std::string("hello")),
bind(&server::write_handler, this, asio::placeholders::error));
start();
}
void write_handler(const system::error_code& ec)
{
cout << "send msg ok\n";
}
private:
ip::tcp::acceptor acceptor;
}; void async_server_test()
{
server ser;
g_ios.run();
} void DNS_test()
{
ip::tcp::socket sock(g_ios);
ip::tcp::resolver rlv(sock.get_io_service()); ip::tcp::resolver::query qry("www.baidu.com", lexical_cast<std::string>());
ip::tcp::resolver::iterator iter = rlv.resolve(qry);
ip::tcp::resolver::iterator end; system::error_code ec = error::host_not_found;
for ( ; ec && iter != end; ++iter)
{
sock.close();
sock.connect(*iter, ec);
}
if ( ec )
{
cout << "can't connect\n";
}
}
8.2 client
#pragma once
#include <vector> #include "boost/thread.hpp"
#include "boost/asio.hpp"
#include "boost/date_time/posix_time/posix_time.hpp" using namespace boost;
using namespace boost::asio;
using namespace std; boost::asio::io_service g_ios; //所有的asio都要有个ios //客户端
void client_test()
{
while ()
{
ip::tcp::socket sock(g_ios);
ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), );
sock.connect(ep); std::string str;
str.resize(, );
sock.read_some(buffer(str));
cout << "receive from " << sock.remote_endpoint().address() << endl;
cout << "content : " << str << endl; sock.close(); boost::this_thread::sleep_for(boost::chrono::seconds());
} } //异步通信客户端
typedef boost::shared_ptr<ip::tcp::socket> sock_ptr;
typedef boost::shared_ptr<std::string> str_ptr;
class client
{
public:
client() : ep(ip::address::from_string("127.0.0.1"), )
{
start();
}
void start()
{
sock_ptr sock(new ip::tcp::socket(g_ios));
sock->async_connect(ep,
bind(&client::connect_handler, this, asio::placeholders::error, sock));
}
void connect_handler(const system::error_code& ec,
sock_ptr sock)
{
if (ec)
{
return;
}
cout << "sock connect " << sock->remote_endpoint().address() << endl;
str_ptr pstr(new std::string(,));
sock->async_read_some(asio::buffer(*pstr),
bind(&client::read_hander, this, asio::placeholders::error, pstr));
start();
}
virtual void read_hander(const system::error_code& ec,
shared_ptr<std::string> str)
{
cout <<"recv msg: " <<str << endl;
}
protected:
ip::tcp::endpoint ep;
}; class client11 : public client
{
virtual void read_hander(const system::error_code& ec,
shared_ptr<std::string> str)
{
cout <<"child recv msg: " <<str << endl;
}
}; void async_client_test()
{
client11 cli;
g_ios.run();
}
9 源码
1-8的源码地址:https://download.csdn.net/download/honggangqianren/10538015