c++ boost库学习三:实用工具

时间:2023-03-09 16:25:31
c++ boost库学习三:实用工具

noncopyable

大家都知道定义一个空类的时候,它实际包含了构造函数,拷贝构造函数,赋值操作符和析构函数等。

这样就很容易产生一个问题,就是当用户调用A a(“^_^") 或者A c="^_^" 时会发生一些意想不到的行为,所以很多时候我们需要禁用这样的用法。

一种方法就是把拷贝构造函数和赋值操作符显式的定义为private,但是这样需要很多代码。

于是boost库为大家提供了一个简单的方法:只需要将类继承于noncopyable就可以了。

#include "iostream"
#include <string>
#include <boost\noncopyable.hpp>
using namespace std; class A:public boost::noncopyable
{
//public:
// A(){};
// A(const A&a){cout<<"call copy constructor"<<endl;}
}; int _tmain(int argc, _TCHAR* argv[])
{
A a;
A b(a); //error
A c;
c=a; //error
return ;
}

经过测试,如果显式的把拷贝构造函数和赋值操作符定义为public的话,noncopyable就失效了。

assign

用过vector等容器的都知道向vector里添加元素可以用insert或push_back方法,但这些方法都太复杂了。

boost库为大家提供了一个简单的方法assign,看过它的用法后你就知道它真的很方便

#include "iostream"
#include <string>
#include <map>
#include <list>
#include <boost\assign.hpp>
using namespace std;
using namespace boost::assign; int _tmain(int argc, _TCHAR* argv[])
{
// += 操作符
vector<string> v;
v+= "aa","bb","cc";
map<int,string> m;
m+=make_pair(,"java"),make_pair(,"python"); // assign的push_back(), push_front(), insert()
vector<int> v2;
push_back(v2) ()()();
list<string> l;
push_front(l) ("aa")("bb")("cc");
map<int,string> m2; //push_back 和 push_front只能用在拥有同名方法的容器里
insert(m2) (,"java")(,"c++");
return ;
}

uuid

uuid就是机器的唯一识别码,一共有128位(16字节)。用uuid可以生成全球唯一的标识,这个东西在写程序的时候会经常用到,比如一款软件的序列号只能用在1台机器上时它就是靠识别uuid来判断的。

可以把uuid看作一个16字节长元素类型为unsign char的容器。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <assert.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
using namespace boost::uuids;
using namespace std;
int main()
{
uuid u;
assert(u.static_size()==);
assert(u.size()==);
vector<unsigned char> v(,);
copy(v.begin(),v.end(),u.begin());
cout<<u<<endl; // uuid生成算法
uuid u2 = random_generator()(); //随机生成一个不重复的uuid
assert(!u2.is_nil()); //判断是否无效uuid
assert(u!=u2);
cout<<u2<<endl; // uuid与字符串的转换
uuid u3 = string_generator()("01234567-89ab-cdef-0123-456789abcdef");
stringstream ss;
ss<<u3;
string s;
ss>>s;
cout<<s<<endl; return ;
}

在vs中编译上面的代码时候可能会报warning C4996错,这时候有两种方法可以解决此问题

1. 需要向文件最开头(我有stdafx.h所以在里面加)里加上#define _SCL_SECURE_NO_WARNINGS,可参考

http://choorucode.com/2010/08/30/visual-c-c4996-warning-on-copy-with-array-parameters/,

2. 在所有#include之前(不包括stdafx.h)加上#include <boost\config\warning_disable.hpp>,其作用是避免VC编译器在使用已经deprecated函数的时候会出现c4996 error从而无法编译通过

比如下面的例子:

#include <boost\config\warning_disable.hpp>
#include <iostream>
using namespace std; int main()
{
char s[]="teststr";
char *s2=new char[];
strcpy(s2,s);
cout<<s2<<endl;
delete s2; return ;
}