본문 바로가기
교육관련/한화비전 VEDA 수강일지

[VEDA 1기 수강일지] 13일차 - C++ 기초 (6) / mordern C++ :

by 김수효 2024. 7. 31.
수강한 개념

 

예외처리 

- try catch (throw)

 

메모리 누수 발생

#include <iostream>
using namespace std;

class Test
{
	int id;
public : 
	Test(int n) { id = n; cout << "Constructor " << id << endl; }
	~Test() { cout << "Destructor" << id << endl; }
};

void f3()
{
	Test* p = new Test(3);
	throw 10;
	delete p;
}

void f2()
{
	Test* p = new Test(2);
	f3();
	delete p;
}

void f1()
{
	Test* p = new Test(1);
	f2();
	delete p;
}

int main()
{
	try {
		f1();
	}
	catch (int x) {
		cout << "catch " << x << endl;
	}
	cout << "main end" << endl;
}

 

- 메모리 해제가 되지 않음

- 그래서 등장한 것이 스마트 포인터 (모던 c++)

 

예외 클래스

- https://cplusplus.com/reference/exception/

 

C, C++ 링킹

- EXTERN "C" : C 컴파일러로 컴파일 할 것을 지시

//main.cpp
#include <iostream>
using namespace std;

extern "C" 
{
	void f();
}

int main()
{
	f();
}


//f.c
#include <stdio.h>

void f()
{
	printf("Hello f\n");
}

Mordern C++

 

스마트 포인터

- unique_ptr : 특정 객체를 한 포인터만 가리킴. 대입 연산 불가

ㄴunique_ptr<클래스> 포인터명 = make_unique<클래스>(인수); //new 사용 지양

int* p1 = new int;
int* p2 = p1; // 가능

unique_ptr<T> ptr = make_unique<T>();
unique_ptr<T> ptr1 = make_unique<T>();
ptr1 = ptr; //불가능

ㄴ 포인터가 해제되면 자동으로 메모리 해제

 

-shared_ptr : 포인터가 사용될때마다 reference count 올림, reference count가 0이면 메모리 해제

 

-weak_ptr : 순환참조 문제 해결용. 멤버함수 lock() 이용, 스레드 등에서 유용

#include <iostream>
#include <memory>
using namespace std;

class Node
{
public:
	weak_ptr<Node> next;
	//shared_ptr<Node> next; 
	Node() { cout << "Node create" << endl; }
	~Node() { cout << "Node destroy" << endl; }
};

int main()
{
	shared_ptr<Node> p1 = make_shared<Node>();
	shared_ptr<Node> p2 = make_shared<Node>();
	p1->next = p2;
	p2->next = p1; //순환 참조 발생!
}

 

범위기반 for 루프

 

constexpr 

- 매크로 비슷한 거 (상수 표현식)

 

형 변환 연산자

- const_cast : const 속성 제거를 위한 형변환에 사용

- static_cast :  컴파일 시 자동 형변환이 가능한지 검사

- dynamic_cast : 실행시간에 형 변환이 가능한지 검사

#include <iostream>
#include <typeinfo>
using namespace std;

class P
{
public:
	P(){}
	virtual ~P() {}
	virtual void show() { cout << "Parant show" << endl; }
};

class C : public P
{
public :
	C() {}
	~C() {}
	void show() { cout << "child show" << endl; }
};

int main()
{
	P* ptr = new C();
	C* cptr = dynamic_cast<C*> (ptr);

	if (cptr == nullptr)
		cout << "casting fail\n"; 
	else
	{
		cout << "casting success\n"; cptr->show();
	}
}

 

- reinterpret_cast

 

 

문제 구현 / 개선방안

 

벡터입력, 예외처리, 스마트포인터 실습

#include "woman.h"

int main()
{
	vector<shared_ptr<Human>> h;
	string s; int c; int n;
	shared_ptr<Human> p = make_shared<Human>();

	while (true)
	{
		//이름, 나이
		cout << "name : ";
		cin >> s;
		cout << "age (20000 -> exit) : ";
		cin >> n;
		if (n == 20000) break;

		//나이가 음수일때 예외처리
		try { if (n < 0) throw n; }
		catch (int x) { cout << "wrong input type" << endl; continue; }

		//성별선택
		cout << "select (1 : man / 2 : woman) : ";
		cin >> c;
		if (c == 1) h.push_back(shared_ptr<Human>(new Man(s,n)));
		else if(c == 2) h.push_back(shared_ptr<Human>(new Woman(s,n)));
	}

	for (auto a : h)
	{
		a->show();
	}
	

	return 0;
}

 

 

기타 사항

 

 


VEDA 바로가기 : www.vedacademy.co.kr

VEDA(한화비전 아카데미) 영상으로 확인하기 : https://url.kr/zy9afd

본 후기는 VEDA(한화비전 아카데미) 1기 학습 기록으로 작성되었습니다.

 

#VEDA #개발의한계를veda #한화비전 #엣지디바이스 #한화비전아카데미 #KDT

 

 

댓글