게임 개발자를 위한 C++ 문법 2-1, 2

1. WHAT
스마트 포인터
- unique_ptr : 객체에 대한 단일 소유권 관리, move -> 소유권 이동
// unique_ptr 생성
unique_ptr<int> ptr1 = make_unique<int>(20);
// 소유권 이동 (move 사용)
unique_ptr<int> ptr2 = move(ptr1);
- shared_ptr : 레퍼런스 카운트 관리, 카운트가 0이 되면 자동으로 메모리 해제
// shared_ptr 생성
shared_ptr<int> ptr1 = make_shared<int>(10);
// ptr1의 참조 카운트 출력, 객체를 참조하는 포인터 수 확인
cout << "ptr1의 참조 카운트: " << ptr1.use_count() << endl; // 출력: 1
// ptr2가 ptr1과 리소스를 공유
shared_ptr<int> ptr2 = ptr1;
cout << "ptr2 생성 후 참조 카운트: " << ptr1.use_count() << endl; // 출력: 2
// ptr2가 범위를 벗어나면 참조 카운트 감소
ptr2.reset(); // 객체 소유 해제, 객체 변경
cout << "ptr2 해제 후 참조 카운트: " << ptr1.use_count() << endl; // 출력: 1
- weak_ptr : 객체의 소유권을 공유하지 않음, 참조 카운트 증가 X
class B {
public:
weak_ptr<A> a_ptr; //B는 A를 소유하지 않음, 참조만 함
void useA() {
if (auto a_shared = a_ptr.lock()) { // 유효한지 확인
a_shared->say_hello();
}
else {
cout << "A is no longer available.\n";
}
}
};
클래스 객체 unique_ptr 관리
#include <iostream>
#include <memory>
using namespace std;
class MyClass {
public:
MyClass(int val) : value(val) {
cout << "MyClass 생성: " << value << endl;
}
~MyClass() {
cout << "MyClass 소멸: " << value << endl;
}
void display() const {
cout << "값: " << value << endl;
}
private:
int value;
};
int main() {
// unique_ptr로 MyClass 객체 관리
unique_ptr<MyClass> myObject = make_unique<MyClass>(42);
// MyClass 멤버 함수 호출
myObject->display();
// 소유권 이동
unique_ptr<MyClass> newOwner = move(myObject);
if (!myObject) {
cout << "myObject는 이제 비어 있습니다." << endl;
}
newOwner->display();
// 범위를 벗어나면 newOwner가 관리하는 메모리 자동 해제
return 0;
}
~MyClass()
힙 메모리
┌────────────────────┐
│ MyClass 객체 │
│ value = 42 │ ← 이 덩어리 전체가 delete됨
└────────────────────┘
더보기
처음에는 소멸자가 포인터가 소멸될 때로 생각하고 myObject는 언제 소멸되지 했는데.. 객체(42)가 소멸되는 거였다 ㅎㅎㅎ 개념과 용어 확실하게 잡고 가야겠다.
클래스 객체 shared_ptr 관리
#include <iostream>
#include <memory>
using namespace std;
class MyClass {
public:
MyClass(int val) : value(val) {
cout << "MyClass 생성: " << value << endl; // 출력: MyClass 생성: 42
}
~MyClass() {
cout << "MyClass 소멸: " << value << endl; // 출력: MyClass 소멸: 42
}
void display() const {
cout << "값: " << value << endl; // 출력: 값: 42
}
private:
int value;
};
int main() {
// shared_ptr로 MyClass 객체 관리
shared_ptr<MyClass> obj1 = make_shared<MyClass>(42);
// 참조 공유
shared_ptr<MyClass> obj2 = obj1;
cout << "obj1과 obj2의 참조 카운트: " << obj1.use_count() << endl; // 출력: 2
obj2->display(); // 출력: 값: 42
// obj2를 해제해도 obj1이 객체를 유지
obj2.reset();
cout << "obj2 해제 후 obj1의 참조 카운트: " << obj1.use_count() << endl; // 출력: 1
return 0;
}
weak_ptr로 순환참조를 해결
#include <iostream>
#include <memory>
using namespace std;
class B; // Forward declaration
class A {
public:
shared_ptr<B> b_ptr;
~A() { cout << "A destroyed\n"; }
};
class B {
public:
weak_ptr<A> a_ptr; // weak_ptr로 변경
~B() { cout << "B destroyed\n"; }
};
int main() {
auto a = make_shared<A>();
auto b = make_shared<B>();
a->b_ptr = b;
b->a_ptr = a; // weak_ptr로 참조
return 0;
}
템플릿
template <typename T> -> 일반화
template <typename T>
T add(T a, T b) {
return a + b;
}
템플릿 클래스
template <typename T>
class Array {
T data[100];
int size;
public:
Array() : size(0) {}
void add(const T& element) {
if(size < 100)
data[size++] = element;
}
void remove() {
if(size > 0)
size--;
}
void print() {
for(int i = 0; i < size; i++)
cout << data[i] << " ";
cout << endl;
}
};
2. RESULT
- 2-1 숙제 2
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Logger {
private:
int logCount;
public:
Logger() :logCount(0) {}
~Logger() {
cout << "Logger instance destroyed." << endl;
}
void logInfo(const string& message) { //const 참조 까먹지 말기
cout << "[INFO]: " << message << endl;
logCount++;
}
void logWarning(const string& message) {
cout << "[WARNING]: " << message << endl;
logCount++;
}
void logError(const string& message) {
cout << "[ERROR]: " << message << endl;
logCount++;
}
void showTotalLogs() {
cout << "Total logs recorded: " << logCount << endl;
}
};
int main() {
unique_ptr<Logger> myLog = make_unique<Logger>();
myLog->logInfo("System is starting");
myLog->logWarning("Low disk space.");
myLog->logError("Unable to connect to the server.");
myLog->showTotalLogs();
return 0;
}
더보기
무의식적으로 계속 콜바이벨류로 함수에 가져오게 된다... ㅠㅠ
const 참조자!!! 쓰자!!!
3. FIX
구글 스타일 가이드 적용
// Copyright 추가, namespace 사용 X, if - else {} 통일, } else로 쓰기, 코드 한 줄 끝 공백 제거,
코드 마지막 엔터 추가, 한글 // NOLINT, 탭 제거, { 다음 주석 공백 두 번 쓰기, 한 줄 80자 이내
https://github.com/yoonseo4343/NBC_Cpp_P1/blob/main/NBC_cpp_P1/main.cpp
NBC_Cpp_P1/NBC_cpp_P1/main.cpp at main · yoonseo4343/NBC_Cpp_P1
내일배움캠프 언리얼7기 과제 1. Contribute to yoonseo4343/NBC_Cpp_P1 development by creating an account on GitHub.
github.com

'내배캠Unreal_TIL > C++' 카테고리의 다른 글
| [TIL] 2025-12-17 | C++ 예외 처리, 연산자 오버로드, 객체지향적 설계 (0) | 2025.12.17 |
|---|---|
| [TIL] 2025-12-16 | C++ STL, vector, map, sort(), find(), Iterator (2) | 2025.12.16 |
| [TIL] 2025-12-12 | 과제1 구현 및 입력 실패 처리, C++ 힙메모리 (0) | 2025.12.12 |
| [C++] Google C++ Style Guide, 구글 코드 컨벤션 (1) | 2025.12.11 |
| [TIL] 2025-12-11 | C++ 객체지향 프로그래밍, 상속과 다형성 (0) | 2025.12.11 |