티스토리 뷰

강의 내용을 무조건 따라하기보다 '어떤 코드가 좋은 코드인가' 부터 먼저 고민봐야 할 것 같다.

 

요약

 

  • 대체할 수 있는 조건부 컴파일은 템플릿으로 기름칠!
  • 매크로는 가급적 사용하지 말고 열거체와 함수로 기름칠!
  • 리소스 관리에는 RAII, 기왕이면 스마트 포인터로 기름칠!
  • 일회성으로 사용하는 함수는 람다식으로 기름칠!
  • 복잡한 타입에는 auto로 기름칠!
  • 반복 횟수에 고통받지 말고 범위 기반 for문으로 기름칠!

 

참고

 

 

예)

기존 C++ 코드

// circle and shape are user-defined types
circle* p = new circle(42);
vector<shape*> v = load_shapes();

for (vector<circle*>::iterator i = v.begin(); i != v.end(); ++i)
{
 if (*i && **i == *p)
  cout << **i << " is a match\n";
}

for (vector<circle*>::iterator i = v.begin(); i != v.end(); ++i)
{
 delete *i; // not exception safe
}

delete p

 

모던 C++ 코드

// circle and shape are user-defined types
auto p = make_shared<circle>(42);
vector<shared_ptr<shape>> v = load_shapes();

for_each(begin(v), end(v), [&](const shared_ptr<shape>& s)
{
 if (s && *s == *p)
  cout << *s << " is a match\n";
})

 

 

 

 

 

 

 

- James Song

댓글