개발/C·C++
-
스마트 포인터개발/C·C++ 2021. 9. 19. 17:33
포인터는 C++ 입문자들에게 첫 번째 장벽이면서 C++ 개발자들이 평생 신경 써야 하는 존재입니다. Java와 C#은 자동으로 메모리를 관리해주지만 C++은 개발자가 관리해야 하죠. 하지만 Raw pointer을 전부 일일이 관리할 수 없기 때문에 스마트 포인터를 잘 활용해야 합니다. 스마트 포인터는 지역 변수의 생명 주기를 이용하는 클래스입니다. 소멸자를 통해서 메모리를 해제시켜주기 때문에 직접 delete를 이용하는 것보단 부담이 덜합니다. 여기서 중요한 것은 부담이 덜하다는 것이지 완전히 사라지는 것이 아니라는 점입니다. unique_ptr은 이름에서 알 수 있듯 포인터가 유일하게 하나만 존재할 수 있도록 복사를 막아놨습니다. shared_ptr은 신경 써서 사용해야 합니다. 내부적으로 참조 카운트..
-
스레드 함수를 람다식 안에서 사용할 때 주의할 점개발/C·C++ 2021. 9. 15. 01:08
void ThreadManager::launch(function callback) { _threads.push_back(thread([&]() { callback(); })); } 위의 코드에는 문제점이 있습니다. 각 스레드가 실행되면서 callback()을 호출하다가 오류가 발생합니다. 사실 굉장히 간단한 문제인데요. launch 함수의 인자인 callback은 지역 변수입니다. launch()가 종료되면 사라지는 것이지요. 하지만 스레드는 계속 작동해야 합니다. 이런 상황에서 스레드 함수를 지역 변수(함수 포인터)의 참조로 받았기 때문에 launch()가 반환되면서 dangling이 일어나기 때문에 오류가 발생합니다.
-
split()개발/C·C++ 2021. 9. 11. 23:26
C#, Java, JavaScript에 있는 문자열 자르기 함수인 split()이 C++에는 없습니다. 필요하면 만들어 써야 합니다. 막상 급하게 필요할 때 문자열 함수가 익숙하지 않다면 생각보다 오래 걸릴 수 있습니다. 미리 만들어서 사용합시다. split() vector split(string s, string delim) { size_t off = 0; vector result; while (true) { size_t pos = s.find(delim, off); size_t count = pos - off; string str = s.substr(off, count); result.push_back(str); off += count + 1; if (0 == off) break; } return r..
-
생산자/소비자 패턴에서의 WaitForSingleObject()개발/C·C++ 2021. 9. 1. 18:36
윈도우에서 제공하는 이벤트 객체와 WaitForSingleObject()를 통해서 실행순서를 동기화할 수 있습니다. 이것이 중요한 이유는 소비자 스레드는 생산자 스레드에서 큐 자료구조에 데이터를 넣어줘야 그 데이터를 꺼내서 필요한 작업을 할 수 있는데, 대기 시간이 길어질 경우 소비자 스레드가 무한 대기하는 것은 효율적으로 CPU를 사용하는 것이 아니기 때문입니다. 대기하는 것에만 CPU 시간을 쓰는 것은 아깝습니다. mutex m; queue q; HANDLE handle; void Producer() { while (true) { { unique_lock lock(m); q.push(100); } this_thread::sleep_for(100ms); } } void Consumer() { while..
-
sleep_for(), yield()개발/C·C++ 2021. 9. 1. 16:43
를 인클루드하면 사용할 수 있는 sleep_for()과 yield()는 같은 듯 다릅니다. sleep_for() 함수를 호출한 스레드는 괄호 안의 시간만큼 스레드가 블락(block)됩니다. 블락이 끝나면 해당 스레드는 준비 큐에 들어가서 CPU 스케줄링에 의해 선택되기를 기다려야 합니다. yield() 함수는 해당 스레드가 블락되지 않고 해당 스레드에 할당된 CPU를 커널에 양도할 수 있도록 사용하는 OS에 힌트를 줍니다. 스레드가 바로 준비 상태가 된다고 볼 수 있죠. 그러므로 yield()는 sleep_for(0ms)와 동일하게 기능합니다. 하지만 굳이 인자를 넘겨야 하는 함수보다는 yield()를 호출하는 게 낫지 않을까 싶습니다. >>출처 https://en.cppreference.com/w/cp..
-
비주얼 스튜디오에서 다른 프로젝트의 파일 참조하기개발/C·C++ 2021. 8. 31. 22:17
다른 프로젝트의 헤더 파일 사용하기 A 프로젝트에서 B 프로젝트의 C.h를 마치 자신의 프로젝트에 있는 것처럼 인클루드해서 사용할 수 있습니다. A 프로젝트의 속성에서 [VC++ 디렉터리]를 가보면 포함 디렉터리를 설정할 수 있는데 B 프로젝트의 폴더를 지정하면 됩니다. 정확히는 C.h가 있는 폴더를 지정하면 됩니다. 다른 프로젝트 라이브러리 참조하기 여러가지 방법이 있습니다. 그 중 하나입니다. 라이브러리 프로젝트는 프로젝트를 만들 때 동적 라이브러리 혹은 정적 라이브러리 둘 중에 하나를 정해서 생성합니다. 정적 라이브러리 기준입니다. A 프로젝트에서 D 프로젝트(정적 라이브러리 프로젝트)를 컴파일해서 얻은 lib 파일이 있는 폴더를 [VC++ 디렉터리]의 라이브러리 디렉터리에 추가해주면 됩니다. 여기..
-
[Rvalue reference] Forcing Move Semantics(4)개발/C·C++ 2021. 8. 26. 20:15
>> 번역글입니다 >> 의역은 있고 오역이 있을 수 있습니다 >> 출처 http://thbecker.net/articles/rvalue_references/section_04.html C++ 표준의 수정 조항 1조는 "위원회는 C++ 개발자가 자신의 발에 총 쏘는 것을 금지하는 규칙을 만들지 않을 것이다"라고 명시되어 있습니다. 농담을 조금 빼고 말하면, 개발자에게 제어를 더 주는 것과 그들을 부주의에서 지켜주는 것을 논할 때, C++은 제어를 더 제공하는 실수를 범하는 경향이 있습니다. 그 정신에 입각해, C++11은 당신이 rvalue뿐만 아니라, 재량에 따라서 lvalue에도 이동 의미론을 사용할 수 있습니다. 한 가지 좋은 예가 std 라이브러리의 swap 함수입니다. 이전과 마찬가지로, rval..