Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6791814
  • 博文数量: 3857
  • 博客积分: 6409
  • 博客等级: 准将
  • 技术积分: 15948
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-02 16:48
个人简介

迷彩 潜伏 隐蔽 伪装

文章分类

全部博文(3857)

文章存档

2017年(5)

2016年(63)

2015年(927)

2014年(677)

2013年(807)

2012年(1241)

2011年(67)

2010年(7)

2009年(36)

2008年(28)

分类: C/C++

2013-09-30 08:43:57

原文地址:OOP草稿整理 作者:HappyAndrew

做了多年的C++开发和代码review, 最近有点空正好把零散的一些记录给整理放上来,便于以后查阅。不断更新中。。。
 

1.     DRY --- Don't Repeat Yourself

不要重复造轮子,将重复的代码封闭成函数。

2.     RAII --- Resource Acquisition Is Initialization

一个对象应该在其构造时获取资源,在对象生命期控制对资源的访问使之始终保持有效,最后在超出对象生命周期时由析构候释放资源。目的是对于异常退出情况是安全的。如:auto_ptr, scoped_ptr,shared_ptr.

优点:

·         防止资源用完后不被释放。

·         减少代码量。

3.     KISS principle --- Keep It Simple, Stupid

4.     Quick-and-dirty

要找到适合的方案,不能做一个workaround交差。

5.     You aren't gonna need it

只实现你需要的,对一些将来都不需要的东西不要实现。

6.     Rule of three (also in C++)

As Charles Petzold puts it,  "Three or more? use a for!  又叫重复造轮子。当一段代码被重复利用三次时,应该将其封装到函数里。

重复写代码的缺点:

·         增加维护的成本。

Big Three:  destructor, copy constructor, assign operator这三个函数有一个存在其他2个也应该存在。


7.     Use smart pointer instead of raw pointer--前面说的RAII

8.     Use library function instead of iterator.

E.g.

To check whether a value exists in a map, use map::count instead of for(…)

9.     Functor (Functional Object)

A unary function is a function that takes one argument.

a binary function is a function which takes two inputs.


bind1st: This function constructs an unary function object from the binary function object op by binding its first parameter to the fixed value.

bind2nd: To bind the second parameter to a specific value.


Pure function is a pointer and pointers are always evil.

Function object is a object that behaves like function, that’s what we want

点击(此处)折叠或打开

  1. #include <iostream>

  2. using namespace std;
  3. struct IncStruct{
  4.     int& operator()(int& value)
  5.     {
  6.         return (++value);
  7.     }
  8. };
  9. int main()
  10. {
  11.     int i=10;
  12.     IncStruct inc;
  13.     cout<<"i="<<i<<endl;
  14.     inc(i);
  15.     cout<<"i="<<i<<endl;
  16.     inc(inc(inc(i)));
  17.     cout<<"i="<<i<<endl;

  18.     return 0;
  19. }

 

10.     Smart pointer ?bool’ cast

点击(此处)折叠或打开

scoped_ptr> ptr(new object);
if (ptr)
{
    //Do...
}

所有智能指针都称为 ?The Safe Bool Idiom”. 参见:

 

阅读(1017) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~