본문으로 건너뛰기
Previous
Next
C++ 삼원 비교 연산자 | 'Spaceship Operator' 가이드

C++ 삼원 비교 연산자 | 'Spaceship Operator' 가이드

C++ 삼원 비교 연산자 | 'Spaceship Operator' 가이드

이 글의 핵심

C++ 삼원 비교 연산자 - "Spaceship Operator" 가이드. C++ 삼원 비교 연산자의 Spaceship Operator란?, 반환 타입, default 비교를 실전 코드와 함께 설명합니다.

Spaceship Operator란?

C++20의 삼원 비교 연산자 <=>

struct Point {
    int x, y;
    
    // C++20 이전: 6개 연산자 필요
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
    bool operator!=(const Point& other) const {
        return !(*this == other);
    }
    bool operator<(const Point& other) const {
        if (x != other.x) return x < other.x;
        return y < other.y;
    }
    // <=, >, >= 생략...
    
    // C++20: 1개로 모두 생성
    auto operator<=>(const Point&) const = default;
};

반환 타입

#include <compare>

// strong_ordering: 완전 순서
struct Point {
    int x, y;
    auto operator<=>(const Point&) const = default;
    // <, <=, >, >=, ==, != 모두 생성
};

// weak_ordering: 동등하지만 구별 가능
struct CaseInsensitiveString {
    string str;
    
    weak_ordering operator<=>(const CaseInsensitiveString& other) const {
        // 대소문자 무시 비교
        return strcasecmp(str.c_str(), other.str.c_str()) <=> 0;
    }
};

// partial_ordering: 부분 순서 (NaN 등)
struct Float {
    double value;
    
    partial_ordering operator<=>(const Float& other) const {
        return value <=> other.value;
    }
};

default 비교

struct Person {
    string name;
    int age;
    
    // 모든 멤버를 순서대로 비교
    auto operator<=>(const Person&) const = default;
};

Person p1{"Alice", 30};
Person p2{"Bob", 25};

cout << (p1 < p2) << endl;   // name 비교
cout << (p1 == p2) << endl;  // name과 age 모두 비교

실전 예시

예시 1: 기본 사용

struct Student {
    string name;
    int score;
    
    auto operator<=>(const Student&) const = default;
};

int main() {
    Student s1{"Alice", 90};
    Student s2{"Bob", 85};
    
    cout << (s1 < s2) << endl;   // 0 (Alice < Bob는 false)
    cout << (s1 > s2) << endl;   // 1
    cout << (s1 == s2) << endl;  // 0
}

예시 2: 커스텀 비교

struct Student {
    string name;
    int score;
    
    // score로만 비교
    strong_ordering operator<=>(const Student& other) const {
        return score <=> other.score;
    }
    
    // == 는 별도 정의 필요
    bool operator==(const Student& other) const {
        return score == other.score;
    }
};

int main() {
    Student s1{"Alice", 90};
    Student s2{"Bob", 85};
    
    cout << (s1 > s2) << endl;   // 1 (90 > 85)
    
    vector<Student> students = {
        {"Charlie", 75},
        {"Alice", 90},
        {"Bob", 85}
    };
    
    sort(students.begin(), students.end());
    
    for (const auto& s : students) {
        cout << s.name << ": " << s.score << endl;
    }
    // Charlie: 75
    // Bob: 85
    // Alice: 90
}

예시 3: 복합 비교

struct Product {
    string category;
    string name;
    double price;
    
    // category -> name -> price 순으로 비교
    auto operator<=>(const Product& other) const {
        if (auto cmp = category <=> other.category; cmp != 0)
            return cmp;
        if (auto cmp = name <=> other.name; cmp != 0)
            return cmp;
        return price <=> other.price;
    }
    
    bool operator==(const Product& other) const = default;
};

예시 4: 대소문자 무시

struct CaseInsensitiveString {
    string str;
    
    weak_ordering operator<=>(const CaseInsensitiveString& other) const {
        auto toLower =  {
            transform(s.begin(), s.end(), s.begin(), ::tolower);
            return s;
        };
        
        return toLower(str) <=> toLower(other.str);
    }
    
    bool operator==(const CaseInsensitiveString& other) const {
        return (*this <=> other) == 0;
    }
};

int main() {
    CaseInsensitiveString s1{"Hello"};
    CaseInsensitiveString s2{"hello"};
    
    cout << (s1 == s2) << endl;  // 1
}

비교 카테고리

C/C++ 예제 코드입니다.

// strong_ordering: 완전 순서
// a < b, a == b, a > b 중 정확히 하나
int a = 1, b = 2;
auto cmp1 = a <=> b;  // strong_ordering::less

// weak_ordering: 동등하지만 구별 가능
// "Hello"와 "hello"는 동등하지만 다름
weak_ordering cmp2 = weak_ordering::equivalent;

// partial_ordering: 부분 순서
// NaN은 어떤 값과도 비교 불가
double x = 1.0, y = NAN;
auto cmp3 = x <=> y;  // partial_ordering::unordered

자주 발생하는 문제

문제 1: == 생성 안됨

// ❌ == 자동 생성 안됨
struct Point {
    int x, y;
    
    auto operator<=>(const Point& other) const {
        return x <=> other.x;  // y 무시
    }
};

Point p1{1, 2}, p2{1, 3};
// p1 == p2;  // 컴파일 에러

// ✅ == 명시적 정의
struct Point {
    int x, y;
    
    auto operator<=>(const Point& other) const {
        return x <=> other.x;
    }
    
    bool operator==(const Point& other) const = default;
};

문제 2: 타입 불일치

// ❌ 다른 타입 비교
struct A {
    int value;
    auto operator<=>(const A&) const = default;
};

struct B {
    int value;
    auto operator<=>(const B&) const = default;
};

A a{1};
B b{1};
// a == b;  // 컴파일 에러

// ✅ 변환 연산자 또는 명시적 비교

문제 3: 포인터 비교

// ❌ 포인터 주소 비교
struct Node {
    int value;
    Node* next;
    
    auto operator<=>(const Node&) const = default;
    // next는 주소로 비교됨
};

// ✅ 커스텀 비교
struct Node {
    int value;
    Node* next;
    
    auto operator<=>(const Node& other) const {
        return value <=> other.value;
    }
};

default vs 커스텀

// default: 모든 멤버 비교
struct Point {
    int x, y;
    auto operator<=>(const Point&) const = default;
};

// 커스텀: 특정 멤버만 비교
struct Point {
    int x, y;
    
    auto operator<=>(const Point& other) const {
        return x <=> other.x;  // x만 비교
    }
    
    bool operator==(const Point&) const = default;
};

FAQ

Q1: Spaceship Operator는 언제 사용하나요?

A:

  • 정렬 가능한 타입
  • 비교 연산자 간소화
  • C++20 이상

Q2: 모든 연산자 생성?

A: <, <=, >, >= 생성. ==는 별도 정의 필요 (default 가능).

Q3: 성능은?

A: 수동 구현과 동일. 컴파일러 최적화 가능.

Q4: C++20 이전에는?

A: 6개 연산자 수동 구현.

Q5: 반환 타입 선택은?

A:

  • strong_ordering: 완전 순서
  • weak_ordering: 동등 관계
  • partial_ordering: 부분 순서

Q6: Spaceship Operator 학습 리소스는?

A:

  • “C++20 The Complete Guide”
  • cppreference.com
  • “Effective Modern C++“

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

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

관련 글

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

이 부록은 앞선 본문에서 다룬 주제(「C++ 삼원 비교 연산자 | ‘Spaceship Operator’ 가이드」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(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++ 삼원 비교 연산자 | ‘Spaceship Operator’ 가이드」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  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 순서를 권장합니다.


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

C++, spaceship, three-way-comparison, comparison, C++20 등으로 검색하시면 이 글이 도움이 됩니다.