Effective C++ Item 18 Make interfaces easy to use correctly and hard to use incorrectly

1. A good API will provide easy to use interfaces but also provide hard to miss-use interfaces. Usually the later one is more fundamental than that of the previous one. Consider you want to write a data class, there are thousands ways to write it. Here is one example:

class Date {
public:
    Date(int month, int day, int year);
    ...
};

Date(3, 4, 2014);
Date(4, 3, 2014);

Both are OK, but only one is logical right.

Under such situation, a better way to implement that is to constrict clients what they can do and force them to right direction:

class Month {
public:
    static Month Jan() {
        return Month(1);
    }
    ...
private:
    explicit Month(int m);
};

Data d(Month::Mar(), Day(10), Year(2011));

 

2. Let's see another example, suppose your interface returns a dynamic allocated resource and will be deleted after all. There are chances that a programmer will forget to delete it or delete it multi times. So, return a smart pointer would be a great idea.

std::tr1::shared_ptr<Investment> createInvestment() {
    std::tr1::shared_ptr<Investment> retVal(static_cast<Investment>(0),
        getRidOfInvestment());

    retVal = ...; //let retVal point to right object
    return retVal;
}

Besides, smart pointer have another advantage that it will use default or assigned deleter, and you don't need to worry about "cross-DLL problems".

转载于:https://www.cnblogs.com/xinsheng/p/3573809.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值