티스토리 뷰
순서는 읽고 있는 모던 C++ 입문 (저자 : 피터 고츠슐링) 의 목차를 따라 인상적인 내용을 기록하고 있습니다.
1. 변수타입 추론 - auto
1
2
3
4
5
|
int a = 0;
int b = 1;
auto c = a + b;
printf("c = %d\n", c);
|
cs |
변수 타입을 추론할 수 있는 auto가 정말 괜찮습니다. 특히 stl 사용시 끝없이 길어지는 자료형은 auto 한번만 넣으면 깔끔하게 해결되서 특히 더 잘 사용하고 있습니다.
2. 범위 기반 for문
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#include<iostream>
#include <list>
int main()
{
// std container에서 사용하는 범위 기반 for문
std::list<int> multipleOfTwo = {1, 2, 3, 4};
for( auto it : multipleOfTwo)
{
printf("%d\n", it);
}
return 0;
}
|
cs |
기계처럼 쓰던 인덱스 값을 안써도 되서, 너무 편하게 잘 사용하고 있습니다.
3. 스마트 포인터
왜 안썼을까 싶은 거 두번째. shared_ptr를 자주 사용하고 있습니다.
1) unique_ptr
고유 소유권을 가지고 있는 포인터. 포인터가 만료되면 자동으로 메모리를 해제해줍니다. unique_ptr를 사용히면 댕글링 포인터를 방지할 수 있다는 장점이 있습니다. 고유 소유권을 가지고 있기 때문에 move로만 데이터를 옮길 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include <iostream>
#include <memory>
int main()
{
// 선언 방법
std::unique_ptr<int> intArray{new int[3]};
*intArray = 10;
// 포인터 내부의 데이터를 얻는 방법
int *ptr = intArray.get();
// unique_ptr는 고유 소유권을 가지고 있기 때문에 move만 가능하다.
std::unique_ptr<int> intArray2;
intArray2 = std::move(intArray);
// 빌드 에러 발생
//intArray2 = intArray
// c++14 : make_unique 지원
auto intArray3 = std::make_unique<int>();
return 0;
}
|
cs |
스마트 포인터 공통적인 내용이지만, new로 할당하는 것 보단 make_* 로 할당하는게 코드를 보는 면에서나 속도면에서나 좋다고 합니다.
2) shared_ptr
여러 곳에서 공통으로 사용 가능한 메모리를 관리할 수 있습니다. shared_ptr의 reference count가 0이 되면 지워집니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#include <iostream>
#include <memory>
int main()
{
// 선언 방법
std::shared_ptr<int> intArray{new int};
*intArray = 10;
// 포인터 내부의 데이터를 얻는 방법
int *ptr = intArray.get();
// shared_ptr는 move, 복사 둘 다 가능하다.
std::shared_ptr<int> intArray2;
intArray2 = std::move(intArray);
// unique_ptr에서 빌드에러 났던게 여기서는 발생하지 않는다.
intArray2 = intArray;
// 사용자 정의 deleter 추가가 가능하다.
std::shared_ptr<int> intArray3(new int[10], std::default_delete<int[]>());
// c++11에서 지원. new 보다 make_shared를 사용하는게 더 좋다.
// 단 default_delete를 지원하지 않는다. 배열선언시 사용할 수 없음.
auto intArray4 = std::make_shared<int>();
return 0;
}
|
cs |
4. 멤버 변수 기본 값 설정
멤버변수 기본값을 설정할 수 있는 건, 이번에 모던 c++을 따로 공부하면서 알게 되었습니다. 사실 보기에는 기본 생성자에 초기화 값을 넣어두면 좋을 것 같지만, 생각해보면 생성자에 초기화 변수 값을 빠뜨릴 수 있기 때문에 큰 클래스의 경우에는 괜찮게 사용할 것 같긴 합니다.
1
2
3
4
5
6
7
8
9
|
class ClassA
{
public:
ClassA(){};
private:
int a = 0;
int b = 0;
};
|
cs |
'Language > C, C++' 카테고리의 다른 글
내가 몰랐던 C++ 문법들 (0) | 2020.03.31 |
---|