author:
- luixiao1223
title: 接口易用难错
用类代替裸参数
struct Day{
explicit Day(int d)
:val(d){}
int val;
};
struct Month{
explicit Month(int m)
:val(m){}
int val;
};
struct Year{
explicit Year(int y)
:val(y){}
int val;
};
class Date{
public:
Date(const Month& m, const Day& d, const Year& y);// 通过类来限制,可以避免很多错误。
};
// 更好的设计月份类
class Month{
public:
static Month Jan() {return Month(1)}
static Month Feb() {return Month(2)}
private:
explicit Month(int m)
:val(m){}
int val;
};
强制用户来使用智能管理器
Investment* createInvestment();
std::tr1::shared_ptr<Investment> createInvestment();
再来看看 shared_ptr
的第二个参数,可以带一个删除器。
std::tr1::shared_ptr<Investment>
pInv(0, getRidOfInvesment);
如何声明一个空的 shared_ptr
然后赋予新的值。
std::tr1::shared_ptr<Investment> createInvestment()
{
std::tr1::shared_ptr<Investment> retVal(static_cast<Investment *>(0), getRidOfInvesment);
retVal = ...;
return retVal;
}
shared_ptr
不会导致一个问题。这个问题叫做cross-DLL problem.
This problem crops up when an object is created using new in one
dynamically linked library (DLL) but is deleted in a different DLL
shared_ptr
不会出现这个问题是,因为创建的时候带的释放函数,是来自于原来的DLL.
shared_ptr
- 多线程时,为了引用计数修改。加入了mutex。
- 不想要多线程保护的话,可以定义一个预处理命令。