모던 C++ (C++11~C++20) 핵심 문법 치트시트 | auto·람다·스마트 포인터·Concepts 한눈에

모던 C++ (C++11~C++20) 핵심 문법 치트시트 | auto·람다·스마트 포인터·Concepts 한눈에

이 글의 핵심

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

들어가며

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

이 글을 읽으면

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

목차

  1. C++11: auto, range-for, 람다, 스마트 포인터
  2. C++14: 제네릭 람다, make_unique
  3. C++17: 구조화된 바인딩, optional, if constexpr
  4. C++20: Concepts, Ranges, Coroutine
  5. 실무 사례
  6. 트러블슈팅
  7. 마무리

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로 코드 품질과 생산성을 크게 향상시킨다.