Wednesday, June 29, 2011

Remind of Effective C++

읽은지 오래되고 한동안 c++를 안쓰다보니 다시 읽고 정리한다.
아마 앞으로 다시 c++를 메인 언어로 사용할 것 같다.


Item 2
Prefer const objects or enums, inline functions to #defines.



Item 3.Use const

int test = 5;

#1.
const int *test = temp; // 값 변경 불가, 주소 값 변경 가능
int const *test = temp; // 위와 같은 의미
*test = 200; // 불가

#2.
int * const test = temp; // 값 변경 가능, 주소 값 변경 불가
*test = 200; // 가능

#3.
int & const test = temp; // 참조가 가르키는 값, 주소 모두 변경 불가

#4.
const my_class instance;
// 내부 멤버변수 전체를 변경 불가능한 클래스 (생성자 함수 제외)
// 모든 내무 멤버 함수는 기본적으로 const 함수
// 내부 함수의 지역 변수 및 인자로 받은 변수는 변경 가능



Item 9. Virtual Function

 - 부모클래스에서 소멸자는 가상함수로 선언
 - 추상 클래스로 활용



Item 18. std::tr1::shared_ptr

std::tr1::shared_ptr createInvestment();
리턴 값을 shared_ptr 영역으로 Investment 타입으로 리턴하지만, 시간이 지나면 자동으로 메모리를 해제한다. (예, automatically unlock mutexes)


Item 20. Prefer pass-by-reference to pass-by-value

 Ex, bool validate_student(const student& s)



Item 22. Never return a pointer or reference to a local stack object.


Item 27. Minimize casting

  - const_cast: constness를 제거하는 일반적인 캐스팅 방법
  - static_cast: implicit conversion시 사용함 (예, int to double)


Item 33. Avoid hiding inherited names

예)
class derived: public base
{
  using base::mf1; // Make all things visible in derived's scope  using base::mf2;  virtual void mf1();
  void mf3();
}

Item 35. Virtual Function을 대체할 수 있는 Strategy Pattern 고려

1) The Strategy Pattern via Function Pointers
 (생략) - 리눅스 커널에서 많이 사용하는 패턴이지만, 난 아무리 생각해도 지저분해보이기만하다.
2) The Strategy Pattern via tr1:function

3) The Classical Strategy Pattern via virtual function (선호)
class GameCharacter;
class Health CalcFunc
{
public:
   ...
   virtual int calc(const GameCharacter& gc) const
   { ...
   }
};
HealthCalcFunc defaultHealthCalc;
class GameCharacter
{
public:
   explicit GameCharacter(HealthCalcFunc *phcf = &defaultHealthCalc) : pHealthCalc(phcf)
  {
  }
  int healthValue() const
  {
     return pHealthCalc->calc(*this);
  }
private:
   HealthCalcFunc *pHealthCalc;

}

0 comments:

Post a Comment