Seminar
TechDays 2015 <녹슨 C++ 코드에 모던 C++로 기름칠하기>
devsong
2016. 1. 13. 18:10
강의 내용을 무조건 따라하기보다 '어떤 코드가 좋은 코드인가' 부터 먼저 고민봐야 할 것 같다.
요약
- 대체할 수 있는 조건부 컴파일은 템플릿으로 기름칠!
- 매크로는 가급적 사용하지 말고 열거체와 함수로 기름칠!
- 리소스 관리에는 RAII, 기왕이면 스마트 포인터로 기름칠!
- 일회성으로 사용하는 함수는 람다식으로 기름칠!
- 복잡한 타입에는 auto로 기름칠!
- 반복 횟수에 고통받지 말고 범위 기반 for문으로 기름칠!
참고
- 모던 C++ 예제 코드
http://www.github.com/utilForever/ModernCpp
- C++ 핵심 가이드라인
영문 : https://github.com/isocpp/CppCoreGuidelines
한글 : https://github.com/CppKorea/CppCoreGuidelines
예)
기존 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