C++ 기본기 연습 프로젝트
카드 덱 조회 프로그램
1. 동적 배열(vector) 직접 구현
답지 안보고 작성한 답안:
#pragma oncetemplate<typename T>class Vector{public: Vector(int _size = 5) : size(_size) { capacity = _size + _size / 2; data = new T[capacity]; } ~Vector() { if (data) { delete[] data; data = nullptr; } } void Add(const T& item) { // 1. check capacity whether full or not if (size == capacity) { // 2. if full expand capacity and move items to new container capacity = capacity + capacity / 2; T* newHouse = new T[capacity]; for (int i = 0; i < capacity; ++i) { newHouse[i] = std::move(data[i]); } delete data; // 힙에 있는 T배열은 어떻게 지움? data = std::move(newHouse); } // 3. if not append on the tail data[size + 1] = item; } void Delete(const T& item) { if (size == 0) return; // 1. find delete target recursively and delete it only once int targetIndex = 0; for (int i = 0; i < size; ++i) { if (data[i] == item) { targetIndex = i; break; } } if (targetIndex) { delete data[targetIndex]; // 2. move left ones forward for (int j = targetIndex + 1; j < size; ++j) data[j - 1] = std::move(data[j]); } }private: int size, capacity; T* data = nullptr;};채점
- data는
T*로 잘 잡았음 size와capacity개념 혼동- 생성자에서
size가 아니라capacity를 받아야 함 Add()에서 반복문을capacity가 아니라size까지만 복사해야함
- 생성자에서
- 배열 포인터 핸들링이 미숙함
- T타입 배열 원소 삭제와 배열 포인터 정리를 혼동하고 있음
- size 증감 누락
- 복사 생성자/대입 연산자 미구현(얕은 복사 위험)
보완
&var와 var.operator->()의 차이
&it: var의 주소
0x1000 : var └── ptr = 0x5000 &var == '0x0000'var.operator->(): var 객체 내부 원소(ptr) 주소
포인터끼리 덧셈 뺄셈은 바이트 단위로 결과가 나오지 않는다
int arr[5] = {10,20,30,40,50}; int* data = arr; // 0x1000, 10int* pos = &arr[2]; // 0x1008, 30pos - data // (0x1008 - 0x1000) / sizeof(int) = 8 / 4 = 2::operator new/delete는 생성자 호출 없이 메모리만 확보한다
T* p = new T;::operator delete(p); // ❌ destructor 안 불림T* p = static_cast<T*>(::operator new(sizeof(T))); delete p; // ❌ 생성자 안 불렸는데 destructor 호출됨ㅈㄱㄴ