首页 > 编程语言 > 详细

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

时间:2014-03-01 03:25:25      阅读:430      评论:0      收藏:0      [点我收藏+]

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:

bubuko.com,布布扣
class Date {
public:
    Date(int month, int day, int year);
    ...
};

Date(3, 4, 2014);
Date(4, 3, 2014);
bubuko.com,布布扣

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:

bubuko.com,布布扣
class Month {
public:
    static Month Jan() {
        return Month(1);
    }
    ...
private:
    explicit Month(int m);
};

Data d(Month::Mar(), Day(10), Year(2011));
bubuko.com,布布扣

 

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.

bubuko.com,布布扣
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;
}
bubuko.com,布布扣

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".

Effective C++ Item 18 Make interfaces easy to use correctly and hard to use incorrectly,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/xinsheng/p/3573809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!