今天开始稍微看下陈硕大湿的mudo代码:
发现很多class开头都冠以:boost::noncopyable
就是防止类被复制,一般的做法是把copy constructor和assign fun为private就ok了。但是会感觉怪怪的。
陈老师这么搞,就是告诉我们:哼哼,我的class拒绝复制。
是的,有简洁的方法为毛不做呢,just do it and hv fun.
比如下面就是简单用法:
#include <boost/noncopyable.hpp>
#include <stdio.h>
#include <string>
#include <iostream>
class Test : boost::noncopyable
{
public:
Test()
{
printf("constructing \n");
}
~Test()
{
printf("destructing\n");
}
const std::string& name() const { return name_; }
void setName(const std::string& n) { name_ = n; }
private:
std::string name_;
};
int main()
{
Test lTest;
Test lTest2(lTest);
// error C2248: “boost::noncopyable_::noncopyable::noncopyable”
//: 无法访问 private 成员(在“boost::noncopyable_::noncopyable”类中声明)
}
亲,不要尝试复制哦,