Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      noexcept specifier(since C++11)

      From cppreference.com
      <cpp‎ |language
       
       
      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
       
      Exceptions
      try block
      Throwing exceptions
      Handling exceptions
      Exception specification
          noexcept specification(C++11)
          dynamic specification(until C++17*)
      noexcept operator(C++11)
       

      Specifies whether a function could throw exceptions.

      Contents

      [edit]Syntax

      noexcept (1)
      noexcept(expression) (2)
      throw() (3)(deprecated in C++17)
      (removed in C++20)
      1) Same asnoexcept(true)
      2) Ifexpression evaluates totrue, the function is declared not to throw any exceptions. A( followingnoexcept is always a part of this form (it can never start an initializer).
      3) Same asnoexcept(true) (seedynamic exception specification for its semantics before C++17)
      expression -contextually converted constant expression of typebool

      [edit]Explanation

      The noexcept-specification is not a part of the function type (just likedynamic exception specification) and can only appear as a part of alambda declarator or a top-levelfunction declarator when declaring functions, variables, non-static data members of type function, pointer to function, reference to function, or pointer to member function, and also when declaring a parameter or a return type in one of those declarations that in turn happens to be a pointer or reference to function. It cannot appear in atypedef ortype alias declaration.

      void f()noexcept;// the function f() does not throwvoid(*fp)()noexcept(false);// fp points to a function that may throwvoid g(void pfa()noexcept);// g takes a pointer to function that doesn't throw// typedef int (*pf)() noexcept; // error
      (until C++17)

      The noexcept-specification is a part of the function type and may appear as part of anyfunction declarator.

      (since C++17)

      Every function in C++ is eithernon-throwing orpotentially throwing:

      • potentially-throwing functions are:
      (until C++17)
      • functions declared withnoexcept specifier whoseexpression evaluates tofalse
      • functions declared withoutnoexcept specifier except for
      • a constructor for a base or member that the implicit definition of the constructor would call ispotentially-throwing (see below)
      • a subexpression of such an initialization, such as a default argument expression, ispotentially-throwing (see below)
      • a default member initializer (for default constructor only) ispotentially-throwing (see below)
      • copy assignment operators,move assignment operators that are implicitly-declared or defaulted on their first declaration unless the invocation of any assignment operator in the implicit definition ispotentially-throwing (see below)
      • comparison operators that are defaulted on their first declaration unless the invocation of any comparison operator in the implicit definition ispotentially-throwing (see below)
      (since C++20)
      • non-throwing functions are all others (those with noexcept specifier whoseexpression evaluates totrue as well as destructors, defaulted special member functions, and deallocation functions)

      Explicit instantiations may use the noexcept specifier, but it is not required. If used, the exception specification must be the same as for all other declarations. A diagnostic is required only if the exception specifications are not the same within a single translation unit.

      Functions differing only in their exception specification cannot be overloaded(just like the return type, exception specification is part of function type, but not part of the function signature)(since C++17).

      void f()noexcept;void f();// error: different exception specificationvoid g()noexcept(false);void g();// ok, both declarations for g are potentially-throwing

      Pointers (including pointers to member function) to non-throwing functionscan be assigned to or used to initialize(until C++17)areimplicitly convertible to(since C++17) pointers to potentially-throwing functions, but not the other way around.

      void ft();// potentially-throwingvoid(*fn)()noexcept= ft;// error

      If a virtual function is non-throwing, all declarations, including the definition, of every overrider must be non-throwing as well, unless the overrider is defined as deleted:

      struct B{virtualvoid f()noexcept;virtualvoid g();virtualvoid h()noexcept= delete;}; struct D: B{void f();// ill-formed: D::f is potentially-throwing, B::f is non-throwingvoid g()noexcept;// OKvoid h()= delete;// OK};

      Non-throwing functions are permitted to call potentially-throwing functions. Whenever an exception is thrown and the search for a handler encounters the outermost block of a non-throwing function, the functionstd::terminate is called:

      externvoid f();// potentially-throwing void g()noexcept{    f();// valid, even if f throwsthrow42;// valid, effectively a call to std::terminate}

      The exception specification of a function template specialization is not instantiated along with the function declaration; it is instantiated only whenneeded (as defined below).

      The exception-specification of an implicitly-declared special member function is also evaluated only when needed (in particular, implicit declaration of a member function of a derived class does not require the exception-specification of a base member function to be instantiated).

      When the noexcept-specification of a function template specialization isneeded, but hasn't yet been instantiated, the dependent names are looked up and any templates used in theexpression are instantiated as if for the declaration of the specialization.

      A noexcept-specification of a function is considered to beneeded in the following contexts:

      • in an expression, where the function is selected by overload resolution
      • the function isodr-used
      • the function would be odr-used but appears in an unevaluated operand
      template<class T>T f()noexcept(sizeof(T)<4); int main(){    decltype(f<void>())*p;// f unevaluated, but noexcept-spec is needed// error because instantiation of the noexcept specification// calculates sizeof(void)}
      • the specification is needed to compare to another function declaration (e.g. on a virtual function overrider or on an explicit specialization of a function template)
      • in a function definition
      • the specification is needed because a defaulted special member function needs to check it in order to decide its own exception specification (this takes place only when the specification of the defaulted special member function is, itself, needed).

      Formal definition ofpotentially-throwing expression (used to determine the default exception specification of destructors, constructors, and assignment operators as described above):

      An expressione ispotentially-throwing if:

      • e is a function call to a function, pointer to function, or pointer to member function which ispotentially-throwing, unlesse is acore constant expression(until C++17)
      • e makes an implicit call to apotentially-throwing function (such as an overloaded operator, an allocation function in anew-expression, a constructor for a function argument, or a destructor ife is a full-expression)
      • e is athrow-expression
      • e is adynamic_cast that casts a polymorphic reference type
      • e is atypeid expression applied to a dereferenced pointer to a polymorphic type
      • e has an immediate subexpression that is potentially-throwing
      struct A{    A(int=(A(5),0))noexcept;    A(const A&)noexcept;    A(A&&)noexcept;    ~A();}; struct B{    B()throw();    B(const B&)=default;// implicit exception specification is noexcept(true)    B(B&&,int=(throw Y(),0))noexcept;    ~B()noexcept(false);}; int n=7;struct D:public A,public B{int* p= newint[n];// D::D() potentially-throwing because of the new operator// D::D(const D&) non-throwing// D::D(D&&) potentially-throwing: the default argument for B’s constructor may throw// D::~D() potentially-throwing // note; if A::~A() were virtual, this program would be ill-formed because an overrider// of a non-throwing virtual cannot be potentially-throwing};

      [edit]Notes

      One of the uses of the constantexpression is (along with thenoexcept operator) to define function templates that declarenoexcept for some types but not others.

      Note that anoexcept specification on a function is not a compile-time check; it is merely a method for a programmer to inform the compiler whether or not a function should throw exceptions. The compiler can use this information to enable certain optimizations on non-throwing functions as well as enable thenoexcept operator, which can check at compile time if a particular expression is declared to throw any exceptions. For example, containers such asstd::vector will move their elements if the elements' move constructor isnoexcept, and copy otherwise (unless the copy constructor is not accessible, but a potentially throwing move constructor is, in which case the strong exception guarantee is waived).

      [edit]Deprecates

      noexcept is an improved version ofthrow(), which is deprecated in C++11. Unlike pre-C++17throw(),noexcept will not callstd::unexpected, may or may not unwind the stack, and will callstd::terminate, which potentially allows the compiler to implementnoexcept without the runtime overhead ofthrow(). As of C++17,throw() is redefined to be an exact equivalent ofnoexcept(true).

      Feature-test macroValueStdFeature
      __cpp_noexcept_function_type201510L(C++17)Make exception specifications be part of the type system

      [edit]Keywords

      noexcept,throw(since C++17)(until C++20)

      [edit]Example

      Run this code
      // whether foo is declared noexcept depends on if the expression// T() will throw any exceptionstemplate<class T>void foo()noexcept(noexcept(T())){} void bar()noexcept(true){}void baz()noexcept{throw42;}// noexcept is the same as noexcept(true) int main(){    foo<int>();// noexcept(noexcept(int())) => noexcept(true), so this is fine     bar();// fine    baz();// compiles, but at runtime this calls std::terminate}

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      CWG 1330C++11an exception specification might be eagerly instantiatedit is only instantiated only if needed
      CWG 1740C++11a( followingnoexcept might start an initializerit can only be a part of
      noexcept specification
      CWG 2039C++11only the expression before conversion is required to be constantthe conversion must also be
      valid in a constant expression

      [edit]See also

      noexcept operator(C++11) determines if an expression throws any exceptions[edit]
      Dynamic exception specification(until C++17) specifies what exceptions are thrown by a function(deprecated in C++11)[edit]
      throw expression signals an error and transfers control to error handler[edit]
      converts the argument to an xvalue if the move constructor does not throw
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/noexcept_spec&oldid=178004"

      [8]ページ先頭

      ©2009-2025 Movatter.jp