Effective STL

21 篇文章 0 订阅

http://book.douban.com/subject/1456960/


(items on) STL efficiency






Item 1: Choose your containers with care


Item 2: Beware the illusion of container-independent code


Item 3: make copying cheap and correct for objects in containers


Item 4: Call empty() instead of checking size() against zero


Item 5: use range member functions: construction, insertion, erasure, assignment


Item 6: be alert for C++ 's most vexing parse

ifstream dataFile("ints.dat");

istream_iterator<int> dataBegin(dataFile);
istream_iterator<int> dataEnd;

list<int> data(dataBegin, dataEnd); // list<int> data(istream_iterator<int>(dataFile), istream_iterator<int>()); does not work


Item 7: when using containers of "new"ed pointers, remember to "delete" the pointers before the container is destroyed.

(destructor for a pointer doesn't call delete)

or use function objects, where templatization added to the operator ()

struct DeleteObject {
    template<typename T> // templatization added here
    void operator()(const T* ptr) const {
        delete ptr;
    }
};
and use it as follows

void doSomething() {
    deque<SpecialString*> dssp;
    ...
    for_each(dssp.begin(), dssp.end(), DeleteObject());
}
This piece of  code is type-safe, but not exception-safe ==> "smart pointers", e.g., Boost's shared_ptr


Item 8: never create containers of auto_ptrs

(no portability, compilers may fail to compile)


Item 9: choose carefully among erasing options



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值