개발/C·C++
-
참조(reference) 변수개발/C·C++ 2021. 4. 17. 17:20
레퍼런스는 변수에 별칭을 붙이는 것입니다. 어셈블리어를 보면 레퍼런스는 포인터와 같습니다. 포인터를 사용하기 쉽게 해주는 문법이라고 봐도 될 것 같습니다. cppreference의 문서에 따르면, 레퍼런스는 객체가 아니기 배열도 있을 수 없고 포인터도 가질 수 없으며 레퍼런스의 레퍼런스도 가질 수 없습니다. 레퍼런스는 기본적으로 변수로 초기화합니다만, 리터럴로 초기화 하는 것도 가능합니다. 이 경우 const를 반드시 붙여야 합니다. 리터럴은 기본적으로 변경될 수 없는 값이기 때문입니다. #include using namespace std; int main() { // int& num = 1 // error const int& num = 1; const string& str = "Test"; } 다음 코..
-
[Dangling Pointer] 유효하지 않은 포인터개발/C·C++ 2021. 4. 10. 20:53
dangle이라는 단어는 동사로 '달랑거리다' 라는 의미를 가집니다. dangling pointer는 메모리가 delete되거나 할당이 해제되어 아무 것도 가리키고 있지 않은 포인터를 말합니다. dangling pointer는 실체가 없이 껍데기만 달랑달랑거리는 포인터인 셈이지요. #include using namespace std; int main() { int* pNum = new int; delete pNum; pNum; // dangling pointer } 출처> en.wikipedia.org/wiki/Dangling_pointer
-
[Pointer] 달과 손가락개발/C·C++ 2021. 4. 10. 17:44
포인터는 주소값을 담는 변수 그 이상 그 이하도 아닙니다. 포인터가 어려운 이유는 주소를 다루는 점 때문에 그렇습니다. 이 모든 건 주소 때문입니다. 개발자가 주소를 직접 다룰 수 있는 언어는, 지금 활발하게 사용되는 언어 중에서는 C/C++가 대표적입니다. typeid를 이용해 타입을 출력해보면 pNum의 공식적인 타입을 확인할 수 있습니다. #include using namespace std; int main() { int num0 = 0; int* pNum = &num0; cout
-
[Enum] 가독성을 위한 약간의 수고개발/C·C++ 2021. 4. 9. 15:31
#include using namespace std; int main() { // 중략 int color = colors[3]; } 직접 확인해보지 않는 한 colors 배열이 네 번째로 가지고 있는 요소의 색상이 무엇인지 알 수 없습니다. 어딘가에 관련 정보를 기록해놓거나 일일이 주석을 달아야 하는 번거로움이 있을 것입니다. 이런 상황에서 enum을 쓰면 좋습니다. enum은 enumeration의 약어이자 C++의 키워드입니다. enumeration의 사전적 의미는 열거입니다. enum을 열거형이라고 하는 이유입니다. #include using namespace std; enum Color { RED, GREEN, BLUE, BLACK, WHITE, SIZE } int main() { // 중략 au..
-
[Cache] 시간 지역성, 공간 지역성개발/C·C++ 2021. 4. 8. 14:19
CPU는 빠르지만 메인 메모리라고 하는 RAM은 느립니다. 둘의 속도 차이는 병목 현상을 만들고 이는 성능 저하의 원인 중 하나입니다. 물론 데이터에 접근할 때 일어나는 컨텍스트 스위칭 역시도 성능에 영향을 주겠지만요. 캐시는 CPU와 램(DRAM) 사이에서 중간자 역할을 합니다. 자주 사용되는 데이터를 캐시에 저장하면 CPU가 빠르게 꺼내어 사용할 수 있습니다. CPU에서 요청한 데이터가 캐시 안에 있을 때 캐시 히트라고 합니다(cache hit). 캐시에 존재하지 않으면 캐스 미스(miss)라고 합니다. 캐시가 효율적으로 동작하기 위해서는 캐시에 저장할 데이터가 지역성(locality)을 가져야 합니다. 지역성은 시간 지역성과 공간 지역성으로 나뉩니다. 시간 지역성은 데이터의 읽기/쓰기를 위해 특정 ..
-
음수 표현(feat.2의 보수)개발/C·C++ 2021. 4. 3. 20:51
2의 보수는 대부분의 산술 연산에서 원래 숫자의 음수처럼 취급됩니다. 2의 보수를 쉽게 구하는 방법은 이진수로 표현된 숫자의 1의 보수를 구한 뒤(각 비트를 반전) 1을 더하는 것입니다. 어렵게 구하는 방법은 8자리 이진수가 있다고 할 때 256(2^8->시작 비트가 2^0부터 시작하므로 9자리 수)에서 해당 수를 뺍니다. 컴퓨터 과학에서는 빼기 연산을 음수를 더하는 방법으로 표현하므로 음수를 구하고 나서 더하는 연산을 합니다. 출처: 위키백과 bit.ly/3mir6SP 2의 보수 - 위키백과, 우리 모두의 백과사전 위키백과, 우리 모두의 백과사전. 2의 보수(--補數, 영어: two's complement)란 어떤 수를 커다란 2의 제곱수에서 빼서 얻은 이진수이다. 2의 보수는 대부분의 산술연산에서 원..