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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | // state.h #pragma once class run; class state { public: state(); ~state(); void foo(run& r); }; // state.cpp #include "stdafx.h" #include "state.h" #include "run.h" state::state() { } state::~state() { } void state::foo(run& r) { r.num++; } // run.h #pragma once #include "state.h" class run { public: state* _state; int num; public: run(); ~run(); void update(); }; // run.cpp #include "stdafx.h" #include "run.h" run::run() { num = 1; } run::~run() { } void run::update() { _state = nullptr; //널 가리키는데... _state = new state; 안해는 _state->foo(*this); //이게 됨? std::cout << num; } // main int _tmain(int argc, _TCHAR* argv[]) { run* rr = new run; rr->update(); return 0; } | cs |
run 클래스에서 state 포인터를 멤버로 갖고
run의 update 함수에서 바로 _state->foo(*this); 사용하면 실행 잘됨 널 넣어도 잘되고 뭐지?
_state 포인터가 가리키는 대상은 쓰레기값이고 널을 넣었으니 널포인터를 가리키는데 어째서 _state -> foo()가 실행 되는거야
아무런 오류도 안뜨고 시벌
타입에 대해 메소드 호출하면 인스턴스가 어떻던간에 메소드 호출되지 않나 - return 0;
근데 new 쓰지마라 - return 0;
foo에서 멤버변수나 this에 접근하려하면 오류날거임
메서드란게 obj.f(p)이런식이면 실제로는 f(&obj, p)이렇게 돌아가는데 &obj가 널포인터라도 접근을 한적이 없어서 문제가 안됨