Effective C++(设计易用难错的接口)


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

  1. 多线程时,为了引用计数修改。加入了mutex。
  2. 不想要多线程保护的话,可以定义一个预处理命令。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值