RAD Studio |  |

Attributes noreturn and final (C++0x)
The noreturn Attribute | The final Attribute | See Also
Collapse All

The C++0x standard includes the addition of attributes that might be applied to the declaration of a class, a general function, a constructor, an array, and so forth. C++Builder 2009 implements two attributes: noreturn and final.

Attributes are set off in the code by double brackets, such as [[noreturn]].

The noreturn Attribute

The noreturn attribute specifies that a function does not return. If a function marked noreturn is called and eventually executes a return statement, the program is considered ill-formed, but the compiler does not issue a message.

For example:

Copy Code

    void f [[noreturn]] () {
       throw “error”;           // OK
    }
    void g [[noreturn]] (int i) {   // ill-formed if called with i<=0
       if (i > 0)
          throw “positive”;
    }

The noreturn attribute is useful for a few library functions that cannot return, such as abort and exit. You can also define your own functions that never return by using the noreturn attribute.

For example:

Copy Code

    void fatal(void) [[noreturn]];
    void fatal(...)
    {
    ...
            exit(1);
    }

The noreturn keyword tells the C++ compiler to assume that fatal cannot return. The compiler can then optimize without regard to what would happen if fatal ever did return. Thus, using noreturn can make better code. More importantly, it helps avoid spurious warnings of uninitialized variables. You cannot assume that registers saved by the calling function are restored before calling the function with the noreturn attribute. It does not make sense for a noreturn function to have a return type other than void.

The final Attribute

The final attribute prevents a class or function from being further inherited. You can add the final attribute to a class definition or to a virtual member function declaration inside a class definition.

A class with the final attribute is not allowed to be a base class for another class. A virtual function with the final attribute is not overridden in a subclass. If the attribute is specified for a class definition, it is equivalent to being specified for each virtual member function of that class, including inherited member functions.

If a virtual member function f in some class B is marked final and in a class D derived from B, a function D::f overrides B::f, the program is ill-formed (the compiler does not issue a message).

For example:

Copy Code

    struct B {
       virtual void f [[ final ]] ();
    };
    struct D : B {
       void f();   // ill-formed
    };

See Also

C++0x Features (C++Builder 2009)

noreturn

final

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!