5

As far as I am aware, there is no [[maybe_noreturn]] attribute in C++.

I have a function which looks like this:

void func() {
    try {
        do_something();
    } catch (const std::exception& e) {
        std::exit(1);
    }
}

If I would mark func as [[noreturn]] I'd run into UB for the happy case. Is it UB when I do not return from a function that is not marked as [[noreturn]]?

Or are there other language constructs, compiler extensions or libraries that implement something like [[maybe_noreturn]]?

flowit
  • 1,382
  • 1
  • 10
  • 36
  • 2
    `[[noreturn]]` may only be used when the function is guaranteed to not return. – JohnFilleau Feb 07 '22 at 15:46
  • What would you like `[[maybe_noreturn]]` to signify? Is this to signal something to the compiler? To the library user? How would I, as another developer, change how I interact with the function if you mark it `[[maybe_noreturn]]`? – JohnFilleau Feb 07 '22 at 15:46
  • 1
    `std::exit` is `[[noreturn]]`, it's enough. – 273K Feb 07 '22 at 15:48
  • See https://stackoverflow.com/a/10538363/2027196 – JohnFilleau Feb 07 '22 at 15:52
  • Aren't functions essentially `maybe_noreturn` by default unless you add a `noexcept` specifier? – Nathan Pierson Feb 07 '22 at 15:52
  • 1
    `noexcept` functions are very much "maybe_noreturn". In fact, they are more likely to terminate than other functions since any exception escaping them will cause them to terminate. – eerorika Feb 07 '22 at 15:59

1 Answers1

6

Is it UB when I do not return from a function that is not marked as [[noreturn]]?

No, it's well defined to terminate the program from a function regardless whether it has [[noreturn]] attribute or not. Using [[noreturn]] is optional when it is appropriate - i.e. when a function terminates unconditionally - but it is always recommended in such cases.

No such attribute as [[maybe_noreturn]] is needed. If it were necessary, then you would find that you would have to declare any function potentially calling [[maybe_noreturn]] function to also be [[maybe_noreturn]], and then functions that call those functions, all the way to the top of the call chain.

eerorika
  • 232,697
  • 12
  • 197
  • 326