개발 소발/개발 C++(기초)
c++ 널 포인터 Null Pointer
우기!
2019. 7. 25. 14:13
포인터의 위험성
포인터에 쓰레기값이 들어가있을때 de-reference할때 문제가 생길 수 있다.
이런문제를 방지하기위해 null pointer가 있다.
nullptr을 사용하여 체크할 수 있다.
double *ptr2 = nullptr;//modern c++
포인터의 주의할점
함수의 파라미터로 선언되어있는 포인터 변수도 복사가 되는것이기에 주소값이 다르다.
즉, 내부에 저장되어있는 주소값은 같지만 포인터 자체변수의
주소값은 다른 파라미터들처럼 복사되어 주소값이 다르다.
잘 생각해보면 당연하다.
#include <iostream>
#include <cstddef>
using namespace std;
void doSomething(double *ptr)
{
if (ptr != nullptr)
{
//nullptr이 아니면 동작해라
cout << ptr << endl;
cout << "address of pointer func() " << &ptr << endl;
//내부의 저장된 주소값은 같다.
cout << "address of pointer func() " << ptr << endl;
}
else
{
cout << "nullPtr" << endl;
}
}
int main()
{
double *ptr = 0;//c-style
double *ptr2 = nullptr;//modern c++
doSomething(ptr2);
doSomething(nullptr);
double d = 3.0;
ptr = &d;
doSomething(ptr);
cout << "address of pointer main() " << &ptr << endl;
//내부의 저장된 주소값은 같다.
cout << "address of pointer main() " << ptr << endl;
std::nullptr_t nptr;//nullptr만 사용할 수 있다.
return 0;
}