Namespaces
Variants

C++ attribute: nodiscard (since C++17)

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

nodiscard 로 선언된 함수나 nodiscard 로 선언된 열거형이나 클래스를 값으로 반환하는 함수가 void 로의 형변환을 제외한 폐기값 표현식 에서 호출되면, 컴파일러는 경고를 발행하도록 권장됩니다.

목차

구문

[ [ nodiscard ] ] (1) (C++17부터)
[ [ nodiscard ( 문자열 리터럴 ) ] ] (2) (C++20부터)
string-literal - 결과가 폐기되어서는 안 되는 이유에 대한 근거를 설명하는 데 사용될 수 있는 평가되지 않은 문자열 리터럴

설명

함수 선언, 열거형 선언 또는 클래스 선언에 나타납니다.

만약, 폐기 값 표현식 void 로의 캐스트를 제외한 다른 표현식에서,

  • nodiscard 로 선언된 함수가 호출되거나,
  • 값으로 반환되는 열거형 또는 클래스가 nodiscard 로 선언된 함수가 호출되거나,
  • nodiscard 로 선언된 생성자가 명시적 형 변환 또는 static_cast 에 의해 호출되거나,
  • nodiscard 로 선언된 열거형 또는 클래스 타입의 객체가 명시적 형 변환 또는 static_cast 에 의해 초기화되는 경우,

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

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

(since C++20)

예제

struct [[nodiscard]] error_info { /*...*/ };
error_info enable_missile_safety_mode() { /*...*/ return {}; }
void launch_missiles() { /*...*/ }
void test_missiles()
{
    enable_missile_safety_mode(); // 컴파일러가 nodiscard 값을 버리는 것에 대해 경고할 수 있음
    launch_missiles();
}
error_info& foo() { static error_info e; /*...*/ return e; }
void f1() { foo(); } // nodiscard 타입이 값으로 반환되지 않음, 경고 없음
// nodiscard( 문자열 리터럴 ) (C++20부터):
[[nodiscard("PURE FUN")]] int strategic_value(int x, int y) { return x ^ y; }
int main()
{
    strategic_value(4, 2); // 컴파일러가 nodiscard 값을 버리는 것에 대해 경고할 수 있음
    auto 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

표준 라이브러리

다음 표준 함수들은 nodiscard 속성으로 선언됩니다:

확장 콘텐츠
할당 함수
할당 함수
(함수)
초기화되지 않은 저장 공간을 할당합니다
( std::allocator<T> 의 public 멤버 함수)
[static]
할당자를 사용하여 초기화되지 않은 저장 공간을 할당합니다
( std::allocator_traits<Alloc> 의 public static 멤버 함수)
메모리 할당
( std::pmr::memory_resource 의 public member function)
메모리 할당
( std::pmr::polymorphic_allocator<T> 의 public 멤버 함수)
외부 할당자를 사용하여 초기화되지 않은 저장 공간을 할당합니다
( std::scoped_allocator_adaptor<OuterAlloc,InnerAlloc...> 의 public 멤버 함수)
간접 접근
(C++17)
포인터 최적화 장벽
(함수 템플릿)
컴파일러에게 포인터가 정렬되어 있음을 알림
(함수 템플릿)
빈 상태 확인 함수
(C++17)
컨테이너가 비어 있는지 확인합니다
(함수 템플릿)
node handle가 비어 있는지 확인합니다
( node handle 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::array<T,N> 의 public 멤버 함수)
문자열이 비어 있는지 확인합니다
( std::basic_string<CharT,Traits,Allocator> 의 public 멤버 함수)
뷰가 비어 있는지 확인합니다
( std::basic_string_view<CharT,Traits> 의 public member function)
컨테이너가 비어 있는지 확인합니다
( std::deque<T,Allocator> 의 public member function)
컨테이너가 비어 있는지 확인합니다
( std::forward_list<T,Allocator> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::list<T,Allocator> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::map<Key,T,Compare,Allocator> 의 public 멤버 함수)
매치가 성공했는지 확인합니다
( std::match_results<BidirIt,Alloc> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::multimap<Key,T,Compare,Allocator> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::multiset<Key,Compare,Allocator> 의 public 멤버 함수)
컨테이너 어댑터가 비어 있는지 확인합니다
( std::priority_queue<T,Container,Compare> 의 public 멤버 함수)
컨테이너 어댑터가 비어 있는지 확인합니다
( std::queue<T,Container> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::set<Key,Compare,Allocator> 의 public 멤버 함수)
시퀀스가 비어 있는지 확인합니다
( std::span<T,Extent> 의 public 멤버 함수)
컨테이너 어댑터가 비어 있는지 확인합니다
( std::stack<T,Container> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::unordered_map<Key,T,Hash,KeyEqual,Allocator> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::unordered_multiset<Key,Hash,KeyEqual,Allocator> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::unordered_set<Key,Hash,KeyEqual,Allocator> 의 public 멤버 함수)
컨테이너가 비어 있는지 확인합니다
( std::vector<T,Allocator> 의 public 멤버 함수)
경로가 비어 있는지 확인
( std::filesystem::path 의 public 멤버 함수)
기타
(C++11)
함수를 비동기적으로(새 스레드에서 실행될 수 있음) 실행하고 결과를 담을 std::future 를 반환함
(함수 템플릿)
(C++26까지)

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
P1771R1 C++17 [[nodiscard]] 생성자에서 효과 없음 생성된 객체가 폐기될 경우 경고 발생 가능

참고문헌

  • C++23 표준 (ISO/IEC 14882:2024):
  • 9.12.9 Nodiscard 속성 [dcl.attr.nodiscard]
  • C++20 표준(ISO/IEC 14882:2020):
  • 9.12.8 Nodiscard 속성 [dcl.attr.nodiscard]
  • C++17 표준 (ISO/IEC 14882:2017):
  • 10.6.7 Nodiscard 속성 [dcl.attr.nodiscard]

참고 항목

(C++11)
tuple tie 로 unpack할 때 요소를 건너뛰기 위한 플레이스홀더
(상수)
C 문서 for nodiscard