c++api-designc++26

Under what scenarios would `std::breakpoint` be used instead of `std::breakpoint_if_debugging`?


Since C++26, std::breakpoint and std::breakpoint_if_debugging is provided. The std::breakpoint is an "unconditional breakpoint", it breaks program whatever debugging mode or not.

From my understanding, breakpoints should only work when the program is running in debug mode. Otherwise, it will never recover since the debugger does not be present.

Does this mean the code below will hang forever without debug mode?

int main()
{
    // Not in debug mode
    std::breakpoint();
    std::cout << "hello, world" << std::endl;
    return 0;
}

Moreover, the revision history shows that the earlier design was indeed a conditional breakpoint.

I found similar designs in LLVM and boost.test. It seems that this design is the mainstream.

So, under what scenarios would std::breakpoint be used instead of std::breakpoint_if_debugging?

In other words, under what scenarios would these breakpoints be used unconditionally instead of checking debug mode? Or am I missing something?


Solution

  • From P2546R5:

    The goal of the std::breakpoint function is to "break" or pause the running program when called. Having an unconditional, i.e. attempts to break even if the debugger is or is not actually monitoring the program allows for use in conditions where it is not possible to detect if a debugger is present.

    (Emphasis mine)

    Considering that the std::breakpoint_if_debugging() is defined as:

    void breakpoint_if_debugging() noexcept {
        if (is_debugger_present()) breakpoint();
    }
    

    It allows you to call std::breakpoint() even if std::is_debugger_present() is wrong, or you want the effect of a breakpoint when you don't have a debugger attached.


    From my understanding, breakpoints should only work when the program is running in debug mode. Otherwise, it will never recover since the debugger does not be present.

    On Linux systems, std::breakpoint() should effectively be asm("int3"), which sends a SIGTRAP. This does not have to be handled by a debugger, you can write your own signal handler for it.

    I think on Windows, it prompts the user to attach a debugger if there isn't one already, which it wouldn't do if you used std::breakpoint_if_debugging()