책 "전문가를 위한 C++" - 1.2 C++의 고급기능
프로그래밍/c,c++ 2021. 1. 28. 11:29"전문가를 위한 C++" 내용 정리
www.yes24.com/Product/Goods/77669043
전문가를 위한 C++
『전문가를 위한 C++』(개정4판)은 새로 추가된 기능과 관련 도구를 비롯해 C++에 대한 모든 내용을 코드와 솔루션 위주로 소개한다. 저자는 실전 프로그래밍에 적용할 수 있는 현실적인 기법을
www.yes24.com
string
#include <string> #include <iostream> using namespace std; int main() { string myString = "Hello, world"; cout << "string is " << myString << endl; cout << "second char is " << myString[1] << endl; return 0; }
포인터와 동적 메모리 - malloc 과 free 대신 new, delete 사용
int* intPtr = nullptr; intPtr = new int; *intPtr = 5; delete intPtr; intPtr = nullptr;
동적으로 배열 할당하기
int arraySize = 8; int* myArray = new int[arraySize]; delete[] myArray; myArray = nullptr;
널 포인터 상수 - NULL 은 0 인지 널 포인터 인지 구분이 되지 않음
#include <iostream> using namespace std; void func(char* str) { cout << "char* " << endl; } void func(int num) { cout << "int " << endl; } int main() { // func(NULL); func(0); func(nullptr); return 0; }
스마트 포인터
스마트 포인터를 사용하면 지정한 객체가 스코프를 벗어나면 메모리가 자동 해제됨(return 문 마다 메모리 해제 필요없음)
std::unique_ptr #include <iostream> #include <memory> using namespace std; class Employee { public: int salary; ~Employee() { cout << "~Employee" << endl; } }; int main() { auto employee = make_unique<Employee>(); if (employee) { cout << "salary " << employee->salary << endl; } auto employees = make_unique<Employee[]>(3); cout << "salary arr " << employees[0].salary << endl; return 0; }
std::shared_ptr 대입연산이 발생할때마다 레퍼런스카운터 증가, 스코프를 벗어 나면 감소, 레퍼런스 카운터가 0 이 되면 메모리 해제됨
auto employee = make_shared<Employee>(); if (employee) { cout << "salary " << employee->salary << endl; }
const 상수 - #define 대신 const 를 사용한다.
레퍼런스 전달 - 일반 변수 처럼 사용하지만 내부적으로 해당 변수에 대한 포인터로 동작한다
int x = 42; int& refer = x; #include <iostream> using namespace std; void inc(int& i) { i++; } int main() { int a = 3; inc(a); inc(3); // ERROR cout << "a = " << a << endl; return 0; }
타입 추론 - auto, decltype
#include <string> #include <iostream> using namespace std; const string message = "TEST"; const string& foo() { return message; } int main() { auto f1 = foo(); cout << "f1 = " << f1 << endl; f1.append("a"); cout << "f1 = " << f1 << endl; cout << "msg = " << message << endl; const auto& f2 = foo(); cout << "f2 = " << f2 << endl; f2.append("a"); cout << "f2 = " << f2 << endl; cout << "msg = " << message << endl; return 0; } #include <string> #include <iostream> using namespace std; const string message = "TEST"; const string& foo() { return message; } int main() { int x = 123; decltype(x) y = 456; decltype(foo()) f2 = foo(); cout << "f2 = " << f2 << endl; f2.append("a"); cout << "f2 = " << f2 << endl; cout << "msg = " << message << endl; return 0; }