Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 nullptr은 정확히 무엇입니까?

<시간/>

이 섹션에서는 C++의 nullptr을 볼 것입니다. nullptr은 포인터 리터럴을 나타냅니다. std::nullptr_t 유형의 prvalue입니다. nullptr에서 모든 포인터 유형의 null 포인터 값 및 멤버 유형에 대한 포인터로의 암시적 변환 속성이 ​​있습니다. 이 개념을 이해하기 위해 하나의 프로그램을 살펴보겠습니다.

예시

#include<iostream>
using namespace std;
int my_func(int N){ //function with integer type parameter
   cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
   cout << "calling function my_func(char *)";
}
int main() {
   my_func(NULL); //it will call my_func(char *), but will generate compiler error
}

출력

[Error] call of overloaded 'my_func(NULL)' is ambiguous
[Note] candidates are:
[Note] int my_func(int)
[Note] int my_func(char*)

그렇다면 위 프로그램의 문제점은 무엇일까요? NULL은 일반적으로 (void*)0으로 정의됩니다. NULL을 정수형으로 변환할 수 있습니다. 따라서 my_func(NULL)의 함수 호출이 모호합니다.

NULL 대신 nullptr을 사용하면 아래와 같은 결과를 얻을 수 있습니다 -

예시

#include<iostream>
using namespace std;
int my_func(int N){ //function with integer type parameter
   cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
   cout << "calling function my_func(char *)";
}
int main() {
   my_func(nullptr); //it will call my_func(char *), but will generate compiler error
}

출력

calling function my_func(char *)

NULL이 예상되는 모든 위치에서 nullptr을 사용할 수 있습니다. NULL과 마찬가지로 nullptr도 모든 포인터 유형으로 변환될 수 있습니다. 그러나 이것은 NULL과 같은 정수 형식으로 암시적으로 변환할 수 없습니다.