Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- C++ class의 궁금증 정리 1
- 일단 다음의 class를 준비
- int idx = 0;
- class C
- {
- public:
- bool b;
- C() : b(false)
- {
- cprintf("C() b=%s,idx=%d",b ? "true" : "false",++idx);
- }
- C(bool _v) : b(_v)
- {
- cprintf("C(bool _v) b=%s,idx=%d",b ? "true" : "false",++idx);
- }
- bool Get() const
- {
- cprintf("Get b=%s,idx=%d",b ? "true" : "false",++idx);
- return b;
- }
- };
- 만약 다음과 같다면 호출되는 순서는
- C a(true),b(false);
- 결과 는 당연히 앞에것부터.
- C(bool _v) b=true,idx=1
- C(bool _v) b=false,idx=2
- C a[] = {false,true,true};
- 위와 같은경우는??
- C(bool _v) b=false,idx=1
- C(bool _v) b=true,idx=2
- C(bool _v) b=true,idx=3
- { } 의 앞에것이 인덱스 0 이고 뒤로 하나씩 증가…
- 이중 궁금한게 있었다.
- c++ 11 부터(???) 사용할 수 있는 for iterator….
- C a[] = {false,true,true};
- for(auto v : a)
- {
- v.Get();
- }
- 와
- C a[] = {false,true,true};
- for(auto &v : a)
- {
- v.Get();
- }
- 이것..
- auto v 가 과연 auto v 와 auto &v 가 차이가 있을까???
- 결과적으로 차이가 없다.
- C(bool _v) b=false,idx=1
- C(bool _v) b=true,idx=2
- C(bool _v) b=true,idx=3 << 여기까지 C a[] ….
- Get b=false,idx=4
- Get b=true,idx=5
- Get b=true,idx=6 << 여기까지 for(auto v: a)
- Get b=false,idx=7
- Get b=true,idx=8
- Get b=true,idx=9 << 여기까지 for(auto &v: a)
- auto v : a 는 auto v = a[i] ; 아닌가???
- 그래서 다음을 테스트
- C a[] = {false,true,true};
- for(int i=0;i<sizeof(a);i++)
- {
- C v = a[i];
- v.Get();
- }
- C(bool _v) b=false,idx=1
- C(bool _v) b=true,idx=2
- C(bool _v) b=true,idx=3
- Get b=false,idx=4
- Get b=true,idx=5
- Get b=true,idx=6
- 음.. C v = a[i] 에서 자기복제 생성자가 호출이 안되는군요….
- C v=a[i] 나 C &v=a[i] 나 상관 없다는 뜻..
- 그러나…. 여기서 다시 궁금증 발동.. 값을 변경하는 write access를 수행해도???
- C a[] = {false,true,true};
- for(auto &v : a)
- {
- v.Get();
- v.b = false;
- }
- for(auto v : a)
- {
- v.Get();
- v.b = false;
- }
- C(bool _v) b=false,idx=1
- C(bool _v) b=true,idx=2
- C(bool _v) b=true,idx=3
- Get b=false,idx=4
- Get b=true,idx=5
- Get b=true,idx=6
- Get b=false,idx=7
- Get b=false,idx=8
- Get b=false,idx=9
- 결과는…. 컴파일러가 너무 똑똑한듯…
- 주소를 직접 찍어보자..
- C a[] = {false,true,true};
- for(auto &v : a)
- {
- cprintf("%d",(uint64_t)&v);
- }
- for(auto v : a)
- {
- cprintf("%d",(uint64_t)&v);
- }
- C(bool _v) b=false,idx=1
- C(bool _v) b=true,idx=2
- C(bool _v) b=true,idx=3
- 1370776
- 1370777
- 1370778
- 1370712
- 1370712
- 1370712
- 음… 분명 다른 주소.. 심지어 auto v: a 는 v의 위치가 한곳으로 고정…
- auto v : a 는 a 값이 그냥 dump 로 v 에 복제되는것이 분명하다.
- 그렇다면……. ?????
- 다음회에 계속………
- [( ̄. ̄)]zZ
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement