C++ 61

[C++] Memory Pool

메모리 풀 구현 32/64/128/... 바이트 단위로 메모리를 미리 할당하여, 실제 할당할 때 해당 메모리를 사용함. 장점 메모리 단편화 문제를 완화 가능. 특히 사이즈가 큰 메모리를 할당할 때 적절한 위치의 페이지를 찾는 것이 시간이 소요될 수 있다. 단점 사용하지 않는 메모리를 미리 할당하여 사용하게 되는 낭비. 메모리 풀과 같이 특정 할당자(Allocator)를 사용한 경우, 메모리를 반납하여 재사용할 수 있도록 할당자를 통한 해제를 해야한다. std::shared_ptr의 생성자에는 해제자 deleter에 대한 인스턴스를 받아 해제를 제어할 수 있다. std::unique_ptr는 타입으로 선언하여 사용한다. 커스텀 deleter를 사용하는 경우 타입 이름이 지저분해질 수 있다. MemoryHe..

C++/Advanced C++ 2024.03.31

[Functional C++] 함수형 프로그래밍 (3) 파셜 어플리케이션과 커링

파셜 어플리케이션과 커링에 대해 알아본다. C++ 17 기준을 요한다. 파셜 어플리케이션 N개의 인자를 가진 함수에서 하나의 인자를 바인딩(결정)하여 N-1개의 인자를 가진 함수를 만들어내는 것. 두 개의 인자를 가지는 add 함수에 첫번째 함수 인자를 결정하여 increment 함수를 만든다. auto add = [](const int first, const int second) { return first + second; }; //auto increment = partialApplication(add, 1); // 위 코드는 다음과 동치이다. auto increment = [](const int second) { return 1 + second; }; C++ 파셜 어플리케이션 기존 함수를 재사용하는 ..

C++/Advanced C++ 2022.10.08

[Functional C++] 함수형 프로그래밍 (2) 합성 함수

람다로 표현할 수 있는 합성 함수를 알아본다. doctest 예시로 들 여러 함수에 대해 유닛 테스트를 수행할 수 있는 헤더만 존재하는 오픈 소스를 사용한다. https://github.com/doctest/doctest GitHub - doctest/doctest: The fastest feature-rich C++11/14/17/20 single-header testing framework The fastest feature-rich C++11/14/17/20 single-header testing framework - GitHub - doctest/doctest: The fastest feature-rich C++11/14/17/20 single-header testing framework gith..

C++/Advanced C++ 2022.10.04

[Functional C++] 함수형 프로그래밍 (1) 불변성과 순수 함수

C++으로 함수형 프로그래밍을 작성하는 방법을 알아본다. 함수형 프로그래밍이 필요한 이유 짝수의 합, 홀수의 합, 모든 합을 구하는 예시 프로그램 struct Sums { int evenSum; int oddSum; int totalSum; }; const Sums sums(const vector& numbers) { Sums theTotals; for (auto iter = numbers.begin(); iter != numbers.end(); ++iter){ int number = *iter; if (number % 2 == 0) theTotals.evenSum += number; if (number % 2 == 1) theTotals.oddSum += number; theTotals.totalSum..

C++/Advanced C++ 2022.10.03

[C++] Protobuf (Google Protocol Buffer) 라이브러리

Protobuf JSON과 같은 메시지 직렬화/역직렬화 라이브러리로 이진 데이터 직렬화로 효율적인 메모리 사용하고 빠른 메시지 파싱 및 다중 언어를 지원한다는 특징이 있다. 메시지의 프로토콜은 .proto 파일로 정의하여 protoc라는 실행 파일로 (cpp의 경우) .pb.h / pb.cc를 자동 생성한다. message Person { optional string name = 1; optional int32 id = 2; optional string email = 3; } Protobuf의 직렬화 원리 다음 글을 읽어보면 좋다. 기본적으로 Key-Value 쌍으로 이루어진 이진 데이터로 인코딩 되는데 https://medium.com/naver-cloud-platform/nbp-%EA%B8%B0%EC..

C++/Advanced C++ 2022.09.27

[Boost] 문자열 다루기

boost 에서 문자열을 다루는 방법을 알아본다. boost::lexical_cast 정수형 실수형 값을 문자열로 바꾸거나 반대로 문자열을 정수형, 실수형 값으로 변환할 때 사용한다. 기본 사용 문자열에서 값으로 변환하기, 타입으로 넘겨준다. auto i = boost::lexical_cast("100"); char chars[] = { 'x', '1', '0', '0', 'y' }; auto i2 = boost::lexical_cast(chars + 1, 3); 해당 변수에 담을 수 없는 값으로 변환하거나 변환이 불가능하다면 boost::bad_lexical_cast를 던진다. try { auto sh = boost::lexical_cast("100000"); } catch (const boost::b..

C++/Boost 2022.08.21

[Boost] thread

boost thread 사용법을 알아본다. 대부분의 기능은 C++11에 표준화되어 헤더에 포함되어 있다. 필요 헤더 #include thread 사용하기 static bool is_first_run() { return true; } static void fill_file(char fill_char, std::size_t size, const char* filename); static void p_example() { if (is_first_run()) { boost::thread(boost::bind(&fill_file, 0, 8 * 1024 * 1024, "save_file.txt")).detach(); } } 실행하고자 하는 함수를 전달하여 스레드를 만들어 실행하도록 한다. detach()는 프로그램..

C++/Boost 2022.08.21

[Boost] any / variant / optional

boost::any C#, JAVA와 같이 모든 타입을 지칭할 수있는 타입을 제공한다. 필요 헤더 #include 모든 타입을 담을 수 있는 클래스 void example2() { boost::any variable(std::string("Hello World!")); // if casting failed, may throw boost::bad_any_cast string s1 = boost::any_cast(variable); // if casting failed, s2 is null string* s2 = boost::any_cast(&variable); } 값에 대한 any_cast는 타입이 맞지 않을 시 boost::bad_any_cast를 던진다. 포인터에 대한 any_cast는 null로 대체..

C++/Boost 2022.08.20

[Boost] program_options

boost의 program_options을 사용해본다. 프로그램 시작 인수를 ./program.exe --option=value 과 같이 실행하고 필요 정보를 출력할 수 있게 해준다. 필요 헤더 #include 사용 방법 1. options_description 개체를 정의를 해준다. 2. 프로그램 인수를 파싱한다. 3. 프로그램 인수를 적용한다. 특징 options_description의 add_option()을 할 때 인수를 필수로 지정하거나 기본값을 지정하는 등을 할 수 있다. ./program.exe --help를 통해 옵션 정보를 출력할 수 있다. .cfg 파일을 통해 인수를 설정할 수 있다. #include "global.h" #ifdef _DEBUG #pragma comment(lib, "l..

C++/Boost 2022.08.20

[Boost] 라이브러리 설치

C++ 고급 기능을 사용할 수 있는 boost 라이브러리를 설치해본다. https://www.boost.org/ Boost C++ Libraries Welcome to Boost.org! Boost provides free peer-reviewed portable C++ source libraries. We emphasize libraries that work well with the C++ Standard Library. Boost libraries are intended to be widely useful, and usable across a broad spectrum of applications www.boost.org 공식 사이트 기준 boost 1.80.0 버전을 사용할 수 있다. 라이브러리 소..

C++/Boost 2022.08.20