C++ weak_ptr
·
C++/Library
weak_ptr weak_ptr 라이브러리 shared_ptr의 순환 의존성 문제를 해결할 수 있다. #include #include class Person { std::string name_; std::weak_ptr partner_; public: Person(const std::string& name) : name_(name) { std::cout
C++ shared_ptr
·
C++/Library
shared_ptr shared_ptr 라이브러리 몇 개의 변수가 포인터를 참조하고 있는지 내부적으로 계산한다. 예제 main.cpp #include #include #include "Resource.h" int main() { Resource* res = new Resource(3); res->setAll(1); { std::shared_ptr ptr1(res); ptr1->print(); { std::shared_ptr ptr2(ptr1); ptr2->setAll(3); ptr2->print(); std::cout print(); std::cout
C++ unique_ptr
·
C++/Library
unique_ptr unique_ptr 라이브러리 scope를 벗어나면 자동으로 메모리를 해제하므로 메모리 누수를 방지할 수 있다. 예제 main.cpp #include #include #include "Resource.h" using namespace std; int main() { std::unique_ptr res(new Resource(100000000)); } /* stdout Resource length constructed Resource destoryed */ Resource.h #pragma once #include class Resource { public: int *data_ = nullptr; unsigned length_ = 0; Resource() { std::cout
C++ std::move
·
C++/Library
std::move 라이브러리 인자로 들어온 값을 R-value로 리턴해준다. 예제 std::move를 사용하지 않은 예제 main.cpp #include #include "Resource.h" #include "AutoPtr.h" using namespace std; int main() { AutoPtr res1(new Resource(10000000)); cout
C++ 출력 스트림 끊기
·
C++/Library
출력 스트림 끊기 라이브러리 사용 std::cout.rdbuf(streambuf *) using streambuf = basic_streambuf; using _Mysb = basic_streambuf; ... _Mysb* __CLR_OR_THIS_CALL rdbuf(_Mysb* _Strbuf) { // set stream buffer pointer _Mysb* _Oldstrbuf = _Mystrbuf; _Mystrbuf = _Strbuf; clear(); return _Oldstrbuf; } 인자로 입력한 stream buffer pointer를 출력 스트림으로 지정한다. 예제 #include using namespace std; int main() { streambuf* orig_buf = cout...
C++ std::exception
·
C++/Library
std::exception 라이브러리 exception 클래스 자식으로 여러 클래스를 가지고 있다. std::exception::what() 함수를 통해 예외 상황을 알 수 있다. 다음과 같이 exception 클래스에서는 가상함수로 정의되어있다. _NODISCARD virtual char const* what() const { return _Data._What ? _Data._What : "Unknown exception"; } https://en.cppreference.com/w/cpp/error/length_error 에 상속 다이어그램이 있으니 참고하면 좋다. #include #include using namespace std; int main() { try { string s; s.resize(..
C++ reference_wrapper
·
C++/Library
reference_wrapper 라이브러리 템플릿 등에 레퍼런스로 전달할 수 있게 해주는 클래스이다. 예제 #include #include #include class Base { public: int i_ = 0; virtual void print() { std::cout
C++ IntArray
·
C++/Library
IntArray int 자료형을 여러개 담을 수 있는 컨테이너 #include class IntArray { int* data_ = nullptr; unsigned length_ = 0; public: IntArray(unsigned length = 0) { initialize(length); } IntArray(const std::initializer_list& list) { initialize(list.size()); int count = 0; for (auto& e : list) data_[count++] = e; } ~IntArray() { delete[] data_; } void initialize(unsigned length) { length_ = length; if (length_ > 0) ..
C++ initializer_list
·
C++/Library
initializer_list C++11 라이브러리 라이브러리 버전에 따라 라이브러리에 들어가 있을 수도, 아닐 수도 있다고 한다. [] 연산자를 사용할 수 없다. foreach문은 내부적으로 iterator를 사용한다. 내부적으로 iterator를 사용하는 foreach문으로 반복문을 구성하면 된다. #include //#include class IntArray { unsigned len_ = 0; int* data_ = nullptr; public: IntArray(unsigned length) : len_(length) { data_ = new int[len_]; } IntArray(const std::initializer_list& list) : IntArray(list.size()) { int ..
C++ chrono
·
C++/Library
chrono 라이브러리 C++11 실행 시간 측정(Run Time Measurement)에 사용되며, 시간을 비교적 정밀하게 측정할 수 있다. #include #include #include #include #include using namespace std; class Timer { using clock_t = std::chrono::high_resolution_clock; using second_t = std::chrono::duration; std::chrono::time_point start_time = clock_t::now(); public: void elapsed() { std::chrono::time_point end_time = clock_t::now(); std::cout
C++ assert
·
C++/Library
assert 라이브러리 assert Debug 모드에서만 런타임에 작동한다. VS의 전처리기 설정에 매크로가 설정되어있다. Debug 모드에서는 _DEBUG Release 모드에서는 NDEBUG 내부 조건이 거짓이면 Debug Error를 발생시킨다. #include int main() { assert(false); } 최대한 나눠서 쓰는게 디버깅하기에 좋다. static assert 컴파일 타임에 작동한다. Release 모드에서도 작동한다. 에러 문구를 넣어야 한다. #include int main() { const int x = 5; //const int x = 4; // 컴파일 안됨 static_assert(x == 5, "x should be 5"); } 릴리즈 모드에선 작동되지 않는다면, 차라..
C++ vector
·
C++/Library
vector 라이브러리 기본 예제 push_back 함수로 벡터의 맨 뒤에 원소를 추가할 수 있다. foreach로 반복문을 작성할 수 있다. (iterator가 존재하기 때문에 사용 가능) #include #include int main() { using namespace std; vector vec; for (int i = 0; i < 10; ++i) vec.push_back(i); for (auto& e : vec) cout
C++ tuple
·
C++/Library
tuple C++11 라이브러리 #include #include std::tuple getTuple() { return (std::make_tuple(10, 3.14)); } int main() { using namespace std; tuple my_tp = getTuple(); cout
C++ array
·
C++/Library
std::array C++11 size(), begin(), end(), at() 등의 함수 사용 가능 at()으로 접근하는 것은 arr[1] 처럼 직접 주소로 접근하는 것보다 느리지만 조금 더 안전하다. at() 함수는 std::exception을 통해 예외 처리가 되어있다. algorithm 라이브러리의 sort 함수 사용 가능
C++ typeinfo
·
C++/Library
데이터 타입 확인 라이브러리의 typeid().name()을 사용한다. cout
C++ cin.ignore
·
C++/Library
입력 버퍼 무시하기 cin.ignore(_Count, _Metadelim) _Count : 무시할 문자의 최대 개수(바이트) 기본 값은 1 정석대로라면 라이브러리의 std::numeric_limits::max()를 사용하는게 맞으나... 귀찮으므로 보통 적당히 큰 수를 채택하는 것 같다. _Metadelim : 이 문자가 나올 때까지 무시한다.(해당 문자 포함) 기본 값은 eof #include int getInt() { while (true) { int x; std::cout > x; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits::max(), &#39;\n&#39;); std::cout op; std::cin...
C++ cin
·
C++/Library
cin 현재 내가 사용하는 윈도우 컴퓨터 기준으로 작성했다. 상속 관계 cin 은 istream 라이브러리 내부 basic_istream 클래스의 객체이다. basic_istream 클래스는 ios 라이브러리 내부 basic_ios 클래스를 상속받는다. basic_ios 클래스는 xiosbase 라이브러리 내부 ios_base 클래스를 상속받는다. ios_base 클래스는 _Iosb 클래스를 상속받는다. #define _CRTIMP2_IMPORT __declspec(dllimport) #define _CRTDATA2_IMPORT _CRTIMP2_IMPORT class _CRTIMP2_PURE_IMPORT ios_base : public _Iosb; class basic_ios : public ios_ba..
C++ 난수 생성 (Random Number Generation)
·
C++/Library
난수 생성 (Random Number Generation) Linear congruential generator 선형 합동 생성기 널리 알려진 유사난수 생성기이다. unsigned int PRNG() // Pseudo Random Number Generator { static unsigned int seed = 5523; // seed number seed = 8253729 * seed + 2396403; return (seed % 32768); } std::rand std::rand() 함수로 나올 수 있는 최댓값인 RAND_MAX를 이용하여 범위를 제한한다. 고르게 분포되지는 않는다. #include int getRandomNumber(int min, int max) { static const dou..
C++ 입력 버퍼 무시하기
·
C++/Library
입력 버퍼 무시하기 cin.ignore(_Count, _Metadelim) _Count : 무시할 문자의 최대 개수(바이트) 기본 값은 1 정석대로라면 라이브러리의 std::numeric_limits::max()를 사용하는게 맞으나... 귀찮으므로 보통 적당히 큰 수를 채택하는 것 같다. _Metadelim : 이 문자가 나올 때까지 무시한다.(해당 문자 포함) 기본 값은 eof #include int getInt() { while (true) { int x; std::cout > x; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits::max(), &#39;\n&#39;); std::cout op; std::cin...
C++ typeinfo
·
C++/Library
데이터 타입 확인 라이브러리의 typeid().name()을 사용한다. cout
C++ 출력 버퍼 비우기
·
C++/Library
출력 버퍼 비우기 (fflush) std::cout