Namespaces
Variants

C attribute: nodiscard (since C23)

From cppreference.net

nodiscard 로 선언된 함수 또는 값으로 반환되는 nodiscard 로 선언된 구조체/공용체/열거형을 반환하는 함수가 폐기값 표현식 에서 호출될 때, void 로의 형변환을 제외하고, 컴파일러는 경고를 발생하도록 권장됩니다.

목차

구문

[[ nodiscard ]]
[[ __nodiscard__ ]]
(1)
[[ nodiscard ( 문자열 리터럴 ) ]]
[[ __nodiscard__ ( 문자열 리터럴 ) ]]
(2)
string-literal - 결과를 폐기하지 말아야 하는 이유를 설명하는 데 사용될 수 있는 텍스트

설명

함수 선언, 열거형 선언, 또는 구조체/공용체 선언에 나타납니다.

만약, discarded-value expression 에서 void 로의 캐스트가 아닌 경우,

  • nodiscard 로 선언된 함수가 호출되거나,
  • nodiscard 로 선언된 구조체/공용체/열거형을 반환하는 함수가 호출되는 경우,

컴파일러가 경고를 발생하도록 권장됩니다.

string-literal 이 지정된 경우, 일반적으로 경고에 포함됩니다.

예제

struct [[nodiscard]] error_info { int status; /*...*/ };
struct error_info enable_missile_safety_mode() { /*...*/ return (struct error_info){0}; }
void launch_missiles() { /*...*/ }
void test_missiles() {
   enable_missile_safety_mode(); // 컴파일러가 nodiscard 값을 버리는 것에 대해 경고할 수 있음
   launch_missiles();
}
struct error_info* foo() { static struct error_info e; /*...*/ return &e; }
void f1() {
    foo(); // nodiscard 타입 자체가 반환되지 않으므로 경고 없음
}
// nodiscard( 문자열 리터럴 ):
[[nodiscard("PURE FUN")]] int strategic_value(int x, int y) { return x ^ y; }
int main()
{
    strategic_value(4,2); // 컴파일러가 nodiscard 값을 버리는 것에 대해 경고할 수 있음
    int z = strategic_value(0,0); // OK: 반환 값이 버려지지 않음
    return z;
}

가능한 출력:

game.cpp:5:4: warning: ignoring return value of function declared with 'nodiscard' attribute
game.cpp:17:5: warning: ignoring return value of function declared with 'nodiscard' attribute: PURE FUN

참고 항목

C++ documentation for nodiscard