2025. 3. 11. 12:22ㆍ프로그래밍 언어/C++
1. 모던 C++이란?
모던 C++(Modern C++)은 C++11 이후의 표준(C++11, C++14, C++17, C++20, C++23)을 기반으로 하는 프로그래밍 스타일과 기능을 의미합니다.
기존 C++98과 C++03의 한계를 개선하여 안전성(Safety), 성능(Performance), 유지보수성(Maintainability), 표현력(Expressiveness)을 높이는 데 중점을 두고 있습니다.
2. 모던 C++의 주요 특징
모던 C++은 코드 간결성, 메모리 관리 자동화, 동시성 지원 강화, 성능 최적화 등의 목표를 위해 여러 기능을 추가했습니다.
2.1 새로운 언어 기능
모던 C++은 기존보다 더 효율적이고 안전한 프로그래밍을 가능하게 하는 기능들을 도입했습니다.
1) 자동 타입 추론 (auto, decltype)
C++11부터 auto를 사용하여 변수 타입을 자동으로 추론할 수 있습니다.
auto x = 42; // int
auto str = "C++"; // const char*
auto pi = 3.14; // double
함수의 반환 타입도 auto를 사용할 수 있습니다.
auto add(int a, int b) {
return a + b;
}
또한, decltype을 사용하면 표현식의 타입을 추론할 수 있습니다.
int a = 10;
decltype(a) b = 20; // b는 int 타입
2) 범위 기반 for 문 (range-based for loop)
C++11부터 for 루프를 보다 간결하게 사용할 수 있습니다.
std::vector<int> vec = {1, 2, 3, 4};
for (auto num : vec) {
std::cout << num << " ";
}
3) nullptr 도입 (C++11)
기존 NULL은 0과 동일하여 타입 안정성이 부족했습니다.
C++11부터 타입이 명확한 nullptr이 도입되었습니다.
int* ptr = nullptr;
4) constexpr 함수 (컴파일 타임 계산, C++11)
constexpr 키워드를 사용하면 컴파일 타임에 계산할 수 있는 함수를 정의할 수 있습니다.
constexpr int square(int x) {
return x * x;
}
constexpr int result = square(5); // 컴파일 타임에 계산됨
이 기능을 활용하면 프로그램 실행 중 불필요한 연산을 줄여 성능 최적화가 가능합니다.
5) 람다 표현식 (Lambda Expressions, C++11)
람다 표현식을 이용하면 간결하고 가독성 높은 코드를 작성할 수 있습니다.
auto add = [](int a, int b) { return a + b; };
int result = add(2, 3); // 5
람다는 캡처(capture) 기능도 지원합니다.
int x = 10;
auto lambda = [x](int y) { return x + y; };
std::cout << lambda(5); // 15
6) 스마트 포인터 (std::unique_ptr, std::shared_ptr)
C++11에서는 new와 delete를 직접 사용하는 대신 스마트 포인터를 이용해 메모리 관리를 자동화할 수 있습니다.
- C++11 (std::unique_ptr)
std::unique_ptr<int> ptr(new int(10));
- C++14 (std::make_unique)
std::unique_ptr<int> ptr = std::make_unique<int>(10);
✔ std::make_unique는 C++14에서 추가되었습니다.
2.2 표준 라이브러리(STL) 개선
C++11 이후 표준 라이브러리(STL)이 크게 확장되었습니다.
- std::array, std::unordered_map: 새로운 컨테이너 추가 (C++11)
- std::chrono: 시간 및 날짜 처리 기능 (C++11)
- std::thread: 멀티스레딩 지원 (C++11)
- std::filesystem: 파일 및 디렉터리 조작 (C++17)
- std::optional, std::variant, std::any: 보다 안전한 데이터 표현 방식 (C++17)
2.3 성능 최적화 및 안전성 강화
모던 C++은 기존 C++보다 성능과 안전성을 강화하는 여러 기능을 도입했습니다.
1) 이동 시멘틱스 (Move Semantics, C++11)
이동 시멘틱스를 활용하면 불필요한 복사를 줄여 성능을 최적화할 수 있습니다.
std::vector<int> vec1 = {1, 2, 3};
std::vector<int> vec2 = std::move(vec1); // vec1의 데이터를 vec2로 이동
2) 완벽 전달 (Perfect Forwarding, C++11)
템플릿 함수에서 매개변수를 그대로 전달하는 기능입니다.
template <typename T>
void wrapper(T&& arg) {
func(std::forward<T>(arg)); // 원본 타입 유지
}
3) 동시성 (std::thread, std::future, std::async, C++11)
C++11부터 멀티스레딩을 표준 라이브러리에서 지원합니다.
#include <thread>
void hello() { std::cout << "Hello, world!\n"; }
std::thread t(hello);
t.join();
4) 코루틴 (Coroutines, C++20)
C++20에서 추가된 코루틴(Coroutines)은 비동기 프로그래밍을 쉽게 만들어 줍니다.
#include <iostream>
#include <coroutine>
struct MyCoroutine {
struct promise_type {
MyCoroutine get_return_object() { return MyCoroutine{std::coroutine_handle<promise_type>::from_promise(*this)}; }
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle;
explicit MyCoroutine(std::coroutine_handle<promise_type> h) : handle(h) {}
~MyCoroutine() { if (handle) handle.destroy(); }
void resume() { handle.resume(); }
};
MyCoroutine exampleCoroutine() {
std::cout << "코루틴 시작" << std::endl;
co_await std::suspend_always{};
std::cout << "코루틴 재개" << std::endl;
}
int main() {
auto coroutine = exampleCoroutine();
std::cout << "메인 함수 실행 중..." << std::endl;
coroutine.resume();
}
3. 결론
모던 C++의 핵심 목표
✔ 안전성 → nullptr, smart pointers, std::optional
✔ 성능 최적화 → move semantics, perfect forwarding
✔ 코드 간결화 → auto, range-based for, lambda
✔ 병렬 처리 지원 → std::thread, std::async, coroutines
모던 C++을 사용하면 더 짧고 효율적인 코드를 작성할 수 있으며, 최신 기술과 요구 사항에 맞게 유지보수가 쉬운 소프트웨어 개발이 가능합니다.
'프로그래밍 언어 > C++' 카테고리의 다른 글
C++ 초급 - 요약 정리 (0) | 2025.02.22 |
---|---|
C++ 초급 - 추가 내용 (심화 학습) (4 - 비동기 프로그래밍 (std::thread, std::async)) (0) | 2025.02.22 |
C++ 초급 - 추가 내용 (심화 학습) (3 - 람다 함수 (lambda expressions)) (0) | 2025.02.22 |
C++ 초급 - 추가 내용 (심화 학습) (2 - 파일 입출력 (fstream)) (0) | 2025.02.22 |
C++ 초급 - 추가 내용 (심화 학습) (1 - 네임스페이스 (namespace)) (0) | 2025.02.22 |