더북(TheBook)

앞서 마트 계산대 시뮬레이션 Ex3_02 예제를 스마트 포인터를 사용해서 어떻게 구현하는지 살펴보자. Customer 클래스는 이전 버전과 같지만, Checkout 클래스의 정의는 스마트 포인터를 사용할 수 있으므로 스마트 포인터로 바꾼다. 이렇게 하면 main() 함수에서도 스마트 포인터를 사용할 수 있다. 포인터 복제본이 필요 없으므로 unique_ptr<T>를 사용하겠다. 새로 정의한 Checkout.h 헤더 파일은 다음과 같다.

// 마트 계산대 - 대기열에 있는 고객에 대해 스마트 포인터를 사용
#ifndef CHECKOUT_H
#define CHECKOUT_H
#include <queue>                 // queue 컨테이너
#include <memory>                // 스마트 포인터
#include “Customer.h”
using PCustomer = std::unique_ptr<Customer>;
 
class Checkout
{
private:
  std::queue<PCustomer> customers;                         // 계산을 기다리는 대기열
 
public:
  void add(PCustomer&& customer) { customers.push(std::move(customer)); }
  size_t qlength() const { return customers.size(); }
 
  // 1분씩 대기 시간을 증가시킨다
  void time_increment()
  {
    if (customers.front()->time_decrement().done())       // 고객이 계산을 끝냈으면…
      customers.pop(); // …대기열에서 제거한다
  };
 
  bool operator<(const Checkout& other) const { return qlength() < other.qlength(); }
  bool operator>(const Checkout& other) const { return qlength() < other.qlength(); }
};
#endif
 

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.