본문으로 건너뛰기
Previous
Next
모던 C++ (C++11~C++20) 핵심 문법 치트시트 | auto·람다

모던 C++ (C++11~C++20) 핵심 문법 치트시트 | auto·람다

모던 C++ (C++11~C++20) 핵심 문법 치트시트 | auto·람다

이 글의 핵심

모던 C++ C++11~C++20 핵심 문법 치트시트. auto, range-for, 람다, 스마트 포인터, optional, variant, Concepts, Ranges 복붙용 요약. 실무·코딩테스트 대비용.

들어가며

모던 C++(C++11 이후)은 auto, 람다, 스마트 포인터, optional, Concepts 등 많은 기능을 도입했습니다. 이 글은 실무에서 진짜 매일 쓰는 것들만 압축해서 한눈에 볼 수 있게 정리한 치트시트입니다.

이 글을 읽으면

  • C++11~C++20의 핵심 문법을 한눈에 파악합니다
  • 실무에서 자주 쓰는 패턴을 복붙용으로 익힙니다
  • 각 버전별 주요 기능을 비교합니다
  • 코딩테스트와 실무에서 바로 쓸 수 있는 코드를 얻습니다

C++11: auto, range-for, 람다, 스마트 포인터

1) auto - 타입 추론

auto x = 42;                    // int
auto d = 3.14;                  // double
auto s = std::string("hello");  // std::string
auto v = std::vector<int>{1, 2, 3};  // std::vector<int>
// 반복자
auto it = v.begin();
// 함수 반환 타입
auto add(int a, int b) -> int {
    return a + b;
}

2) range-based for

std::vector<int> v = {1, 2, 3, 4, 5};
// 읽기
for (int x : v) {
    std::cout << x << std::endl;
}
// 수정
for (int& x : v) {
    x *= 2;
}
// const 참조
for (const auto& x : v) {
    std::cout << x << std::endl;
}

3) 람다 표현식

// 기본
auto add = [](int a, int b) { return a + b; };
std::cout << add(2, 3) << std::endl;  // 5
// 캡처
int factor = 10;
auto multiply = [factor](int x) { return x * factor; };
std::cout << multiply(5) << std::endl;  // 50
// 캡처 방식
[=]   // 값 캡처
[&]   // 참조 캡처
[x]   // x만 값 캡처
[&x]  // x만 참조 캡처

4) 스마트 포인터

#include <memory>
// unique_ptr (단일 소유권)
auto p1 = std::make_unique<int>(42);
std::cout << *p1 << std::endl;
// shared_ptr (공유 소유권)
auto p2 = std::make_shared<int>(42);
auto p3 = p2;  // 참조 카운트 증가
// weak_ptr (순환 참조 방지)
std::weak_ptr<int> wp = p2;
if (auto sp = wp.lock()) {
    std::cout << *sp << std::endl;
}

5) nullptr

// C++98
int* p = NULL;  // 0과 혼동
// C++11
int* p = nullptr;  // 타입 안전

6) 초기화 리스트

std::vector<int> v = {1, 2, 3, 4, 5};
std::map<std::string, int> m = {{"a", 1}, {"b", 2}};

C++14: 제네릭 람다, make_unique

1) 제네릭 람다

auto print = [](auto x) { std::cout << x << std::endl; };
print(42);
print("hello");
print(3.14);

2) make_unique

// C++11
std::unique_ptr<int> p(new int(42));
// C++14
auto p = std::make_unique<int>(42);

3) 반환 타입 추론

auto add(int a, int b) {
    return a + b;  // int 추론
}

C++17: 구조화된 바인딩, optional, if constexpr

1) 구조화된 바인딩

// pair
std::pair<int, std::string> p = {1, "hello"};
auto [id, name] = p;
std::cout << id << ", " << name << std::endl;
// map
std::map<std::string, int> m = {{"a", 1}, {"b", 2}};
for (const auto& [key, value] : m) {
    std::cout << key << ": " << value << std::endl;
}
// tuple
std::tuple<int, double, std::string> t = {1, 3.14, "hello"};
auto [i, d, s] = t;

2) std::optional

#include <optional>
std::optional<int> find(const std::vector<int>& v, int target) {
    for (int x : v) {
        if (x == target) return x;
    }
    return std::nullopt;
}
auto result = find(v, 5);
if (result) {
    std::cout << "찾음: " << *result << std::endl;
} else {
    std::cout << "못 찾음" << std::endl;
}
// value_or
int value = result.value_or(0);

3) std::variant

#include <variant>
std::variant<int, double, std::string> v;
v = 42;
std::cout << std::get<int>(v) << std::endl;
v = 3.14;
std::cout << std::get<double>(v) << std::endl;
v = "hello";
std::cout << std::get<std::string>(v) << std::endl;
// 방문자 패턴
std::visit([](auto&& arg) {
    std::cout << arg << std::endl;
}, v);

4) if constexpr

template<typename T>
void process(T value) {
    if constexpr (std::is_integral_v<T>) {
        std::cout << "정수: " << value << std::endl;
    } else if constexpr (std::is_floating_point_v<T>) {
        std::cout << "실수: " << value << std::endl;
    } else {
        std::cout << "기타: " << value << std::endl;
    }
}
process(42);      // 정수
process(3.14);    // 실수
process("hello"); // 기타

5) 클래스 템플릿 인자 추론

// C++14
std::pair<int, std::string> p(1, "hello");
// C++17
std::pair p(1, "hello");  // 타입 추론
std::vector v{1, 2, 3};   // std::vector<int>

C++20: Concepts, Ranges, Coroutine

1) Concepts

#include <concepts>
template<std::integral T>
T add(T a, T b) {
    return a + b;
}
// 커스텀 Concept
template<typename T>
concept Numeric = std::is_arithmetic_v<T>;
template<Numeric T>
T multiply(T a, T b) {
    return a * b;
}

2) Ranges

#include <ranges>
#include <vector>
#include <iostream>
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 필터 + 변환
auto result = v 
    | std::views::filter([](int x) { return x % 2 == 0; })
    | std::views::transform([](int x) { return x * x; });
for (int x : result) {
    std::cout << x << " ";  // 4 16 36 64 100
}

3) Coroutine

#include <coroutine>
#include <iostream>
struct Generator {
    struct promise_type {
        int current_value;
        
        auto get_return_object() { return Generator{this}; }
        auto initial_suspend() { return std::suspend_always{}; }
        auto final_suspend() noexcept { return std::suspend_always{}; }
        void return_void() {}
        void unhandled_exception() {}
        
        auto yield_value(int value) {
            current_value = value;
            return std::suspend_always{};
        }
    };
    
    std::coroutine_handle<promise_type> handle;
    
    Generator(promise_type* p) : handle(std::coroutine_handle<promise_type>::from_promise(*p)) {}
    ~Generator() { if (handle) handle.destroy(); }
    
    bool next() {
        handle.resume();
        return !handle.done();
    }
    
    int value() { return handle.promise().current_value; }
};
Generator counter(int start, int end) {
    for (int i = start; i <= end; ++i) {
        co_yield i;
    }
}
int main() {
    auto gen = counter(1, 5);
    while (gen.next()) {
        std::cout << gen.value() << " ";  // 1 2 3 4 5
    }
    
    return 0;
}

4) 삼원 비교 연산자 (<=>)

#include <compare>
struct Point {
    int x, y;
    
    auto operator<=>(const Point&) const = default;
};
int main() {
    Point p1{1, 2};
    Point p2{1, 3};
    
    if (p1 < p2) {
        std::cout << "p1 < p2" << std::endl;
    }
    
    return 0;
}

실무 사례

사례 1: 데이터 파싱 - optional 활용

#include <optional>
#include <string>
#include <sstream>
#include <iostream>
std::optional<int> parseInteger(const std::string& str) {
    std::istringstream iss(str);
    int value;
    
    if (iss >> value) {
        return value;
    }
    
    return std::nullopt;
}
int main() {
    auto result1 = parseInteger("42");
    auto result2 = parseInteger("abc");
    
    std::cout << "result1: " << result1.value_or(-1) << std::endl;  // 42
    std::cout << "result2: " << result2.value_or(-1) << std::endl;  // -1
    
    return 0;
}

사례 2: 리소스 관리 - unique_ptr

#include <memory>
#include <fstream>
#include <iostream>
class FileHandler {
private:
    std::unique_ptr<std::ifstream> file;
    
public:
    FileHandler(const std::string& filename) {
        file = std::make_unique<std::ifstream>(filename);
        if (!file->is_open()) {
            throw std::runtime_error("파일 열기 실패");
        }
    }
    
    std::string readLine() {
        std::string line;
        if (std::getline(*file, line)) {
            return line;
        }
        return "";
    }
};
int main() {
    try {
        FileHandler handler("data.txt");
        std::cout << handler.readLine() << std::endl;
    } catch (const std::exception& e) {
        std::cout << "에러: " << e.what() << std::endl;
    }
    
    return 0;
}

사례 3: 알고리즘 - 람다 활용

#include <algorithm>
#include <vector>
#include <iostream>
int main() {
    std::vector<int> v = {5, 2, 8, 1, 9, 3};
    
    // 정렬
    std::sort(v.begin(), v.end(), [](int a, int b) {
        return a > b;  // 내림차순
    });
    
    // 필터
    auto it = std::remove_if(v.begin(), v.end(), [](int x) {
        return x < 5;
    });
    v.erase(it, v.end());
    
    // 출력
    for (int x : v) {
        std::cout << x << " ";  // 9 8 5
    }
    
    return 0;
}

사례 4: 타입 안전 - variant 활용

#include <variant>
#include <string>
#include <iostream>
using Value = std::variant<int, double, std::string>;
void printValue(const Value& v) {
    std::visit([](auto&& arg) {
        using T = std::decay_t<decltype(arg)>;
        if constexpr (std::is_same_v<T, int>) {
            std::cout << "정수: " << arg << std::endl;
        } else if constexpr (std::is_same_v<T, double>) {
            std::cout << "실수: " << arg << std::endl;
        } else if constexpr (std::is_same_v<T, std::string>) {
            std::cout << "문자열: " << arg << std::endl;
        }
    }, v);
}
int main() {
    printValue(42);
    printValue(3.14);
    printValue("hello");
    
    return 0;
}

트러블슈팅

문제 1: auto 남용

증상: 타입이 불명확해 가독성 저하

// ❌ 타입 불명확
auto x = 0;  // int? long?
// ✅ 명시적 타입
int x = 0;
// auto 사용이 좋은 경우
auto it = v.begin();  // 반복자
auto lambda = [](int x) { return x * 2; };

문제 2: 람다 캡처 댕글링

증상: 람다가 유효하지 않은 참조 캡처

// ❌ 댕글링 참조
auto makeLambda() {
    int x = 42;
    return [&x]() { return x; };  // x는 스택에서 사라짐
}
// ✅ 값 캡처
auto makeLambda() {
    int x = 42;
    return [x]() { return x; };
}

문제 3: shared_ptr 순환 참조

증상: 메모리 누수

#include <memory>
struct Node {
    std::shared_ptr<Node> next;
};
// ❌ 순환 참조
auto n1 = std::make_shared<Node>();
auto n2 = std::make_shared<Node>();
n1->next = n2;
n2->next = n1;  // 순환 참조 (메모리 누수)
// ✅ weak_ptr 사용
struct NodeFixed {
    std::weak_ptr<NodeFixed> next;
};

문제 4: optional 값 접근 전 체크 누락

증상: std::bad_optional_access 예외

std::optional<int> opt;
// ❌ 체크 없이 접근
// int x = *opt;  // 예외
// ✅ 체크 후 접근
if (opt) {
    int x = *opt;
}
// 또는 value_or
int x = opt.value_or(0);

마무리

모던 C++코드 품질생산성을 크게 향상시킵니다.

핵심 요약

  1. C++11
    • auto, range-for, 람다, 스마트 포인터
    • nullptr, 초기화 리스트
  2. C++14
    • 제네릭 람다, make_unique
    • 반환 타입 추론
  3. C++17
    • 구조화된 바인딩, optional, variant
    • if constexpr, 클래스 템플릿 인자 추론
  4. C++20
    • Concepts, Ranges, Coroutine
    • 삼원 비교 연산자

도입 순서

단계기능이유
1단계auto, range-for, 스마트 포인터버그 감소
2단계람다, optional코드 간결성
3단계구조화된 바인딩, variant가독성
4단계Concepts, Ranges표현력

버전별 핵심 기능

// C++11
auto x = 42;
for (auto& x : v) { /* ....*/ }
auto lambda = [](int x) { return x * 2; };
auto p = std::make_shared<int>(42);
// C++14
auto print = [](auto x) { std::cout << x; };
auto p = std::make_unique<int>(42);
// C++17
auto [key, value] = map.begin();
std::optional<int> opt = find(v, 5);
if constexpr (std::is_integral_v<T>) { /* ....*/ }
// C++20
template<std::integral T>
T add(T a, T b) { return a + b; }
auto even = v | std::views::filter([](int x) { return x % 2 == 0; });

다음 단계

  • auto와 decltype: C++ auto와 decltype
  • 범위 기반 for: C++ 범위 기반 for문
  • C++ 개요: C++이란?

참고 자료

  • “Effective Modern C++” - Scott Meyers
  • “C++17 The Complete Guide” - Nicolai M. Josuttis
  • “C++20 The Complete Guide” - Nicolai M. Josuttis
  • cppreference: https://en.cppreference.com/ 한 줄 정리: 모던 C++은 auto, 람다, 스마트 포인터, optional, Concepts로 코드 품질과 생산성을 크게 향상시킨다.

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「모던 C++ (C++11~C++20) 핵심 문법 치트시트 | auto·람다·스마트 포인터·Concepts 한눈에」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「모던 C++ (C++11~C++20) 핵심 문법 치트시트 | auto·람다·스마트 포인터·Concepts 한눈에」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. 모던 C++ C++11~C++20 핵심 문법 치트시트. auto, range-for, 람다, 스마트 포인터, optional, variant, Concepts, Ranges 복붙용 요약. 실무·코딩테스트 대비용. S… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, 모던C++, C++11, C++14, C++17, C++20, 치트시트 등으로 검색하시면 이 글이 도움이 됩니다.