개발/C·C++
-
noexcept개발/C·C++ 2022. 1. 6. 20:36
함수는 대부분 noexcept(false)입니다. 절대 예외를 던지지 않는다면 noexcept 키워드를 통해서 설정할 수 있습니다. 함수가 절대 예외를 던지지 않는 경우 동작 중 실패하지 않으므로 실패했을 때의 값을 복원할 필요가 없기 때문에 스택을 준비하지 않아도 됩니다. run stack에서 unwindable state를 유지할 필요가 없습니다. vector의 크기가 capacity와 같아진다면 저장 공간을 동적으로 추가 확보하며 기존 데이터를 새로운 저장 공간으로 옮깁니다. 이동 생성자가 정의되어 있는 경우 데이터를 이동하고 그렇지 않은 경우 복사 생성자를 통해 복사합니다. 이동 생성자는 만약 예외가 일어날 경우 원래 값으로 복구할 수가 없기 때문에(std::move 함수를 통해 rvalue로 만..
-
get 함수를 const로 해야 하는 이유개발/C·C++ 2022. 1. 4. 22:16
객체를 만약 const로 선언한다면 초기화 이후에 내부 데이터를 변경하지 않겠다는 의미입니다. 데이터는 변경할 수 없어도 외부에서 값이 필요할 수는 있습니다. 하지만 get 함수에 const를 붙이지 않는다면 const 객체는 get 함수를 호출할 수 없습니다. 함수를 호출할 때 암시적으로 this 포인터가 전달되므로 const 객체는 const this가 전달됩니다. 이 때 함수가 const가 아니라면 const 포인터는 일반 포인터가 가리킬 수 없기 때문에 함수를 호출할 수가 없는 상황이 됩니다. 다음 그림을 보면 선언되어 있는 getName 함수에 접근하지 못함을 알 수 있습니다. 상수 객체를 생성해야 하는 이유가 있을 텐데 get 함수를 호출하지 못해 상수 객체를 만들지 못하는 상황은 없어야 할 ..
-
알아두면 좋을 개념개발/C·C++ 2022. 1. 3. 21:49
IOCP를 이용한 멀티스레드 네트워크 프로그래밍에서 WSASend가 쉽지 않으며 버퍼 관리도 마찬가지입니다. 환형 버퍼를 사용하는 방법이 있으며 다른 방법은 메모리 풀링을 활용하는 것입니다. 1. 전역 버퍼 매니저를 통해 필요할 때마다 메모리를 할당받고 이 메모리는 쓰임이 다 끝나면(ref_count가 0이 되면) 자동으로 재활용됩니다. make_shared 객체를 만들 때 두 번째 인수로 deleter를 넣을 수 있는데 멤버 함수가 아닌 클래스 스태틱 함수를 넣어주면 됩니다. 반납할 때 매니저 클래스에서 관리하는 벡터 객체에 push_back 해줍니다. 2. 메모리 덩어리는 TLS에서 관리되도록 합니다. 그러면 획득한 메모리에 대해서는 멀티스레드를 신경쓰지 않아도 됩니다. 전역 객체인 버퍼 매니저에서 ..
-
복사 생성자와 이동 생성자개발/C·C++ 2021. 12. 27. 19:56
list aList; aList.push_back(A(1)); 위의 코드는 어떤 생성자가 호출될까요? RVO가 적용될까요? push_back 함수는 값을 인자로 받는 push_back 함수는 오버로딩되어 있지 않습니다. const T& 이거나 T&& 입니다. void push_back(const _Ty& _Val) { _Emplace(_Mypair._Myval2._Myhead, _Val); } void push_back(_Ty&& _Val) { // insert element at end _Emplace(_Mypair._Myval2._Myhead, _STD move(_Val)); } A 클래스에 이동 생성자가 정의되어 있지 않으면 const lvalue reference를 파라미터로 받는 함수가 호출될 ..
-
바이트 정렬개발/C·C++ 2021. 9. 24. 18:15
바이트를 정렬할 때 윈도우에서는 __declspec(align(#))을 지원했지만 이는 언어 상의 표준은 아니었습니다. MS에서 지원해주는 거였죠. C++11부터는 표준으로 alignas를 사용할 수 있습니다. 다음에 적용할 수 있습니다. 클래스, 구조체, 공용체, 열거체의 선언이나 정의부 비트 필드가 아닌 데이터 멤버의 선언부 변수의 선언부(다만 함수의 파라미터와 함수의 예외 파라미터에는 사용할 수 없음 0을 넣는 것은 언제나 무시되고 자연스럽게 정렬된 정렬 값보다 작은 숫자 역시 무시됩니다. 위의 예제에서는 4 이상의 값을 넣어야 합니다. 표준이기 때문에 컴파일 타임에 오류를 잡아주지만, __declspec(align(#))을 사용하면 컴파일 과정에서 해당 정렬이 무시된다는 경고를 콘솔 창에 띄워줍니..
-
union개발/C·C++ 2021. 9. 24. 14:12
구글링을 하면 나오는 union에 관한 얘기 중에 다른 변수에 값을 넣으면 이전에 넣은 데이터가 지워진다는 이야기가 나옵니다. 반은 맞고 반은 틀렸습니다. struct Test { union { int i; struct { unsigned int t1 : 1; unsigned int t2 : 1; unsigned int t3 : 1; unsigned int t4 : 1; unsigned int t5 : 1; unsigned int t6 : 1; } s; } u; }; Test 객체를 만들어서 크기를 보면 4바이트가 나옵니다. union 안에 있는 구조체는 멤버 변수는 1비트만 갖게 했기 때문에 멤버 변수가 32개가 넘지 않는 한 4바이트가 나옵니다. union은 메모리를 공유하기 때문에 마지막으로 덮어씌..