简体   繁体   中英

Sequence points in C++ and exceptions

Can compiler reorder variable setting and throw() op in C++? Or, does standard C++ 14882-1998 allows or prohibit compiler of this transform?

For code:

bool funct()
{
    bool succeeded = false;
    bool res_throw = false;

        try {
            throw("it");
            succeeded = true;
        }
        catch(...) {
            res_throw = true;
        }

        cout << "Result of throw: " << res_throw << endl;
        cout << "succeeded: " << succeeded << endl;

    return succeeded;
}

Can the output be a

Result of throw: true
succeeded: true

The Standard says: "[intro.execution]#7":

modifying an object .. are all side effects, which are changes in the state of the execution environment

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place

Is throw statement a sequence point?

The semicolon is a sequence point. The throw happens before succeeded is set to true

EDIT: To clarify: succeeded will not be set to true

Yes, there is a sequence point associated with the throw statement, because there is a sequence point at the end of every statement.

So succeeded must remain false in your example.

I don't have the C++98 Standard, but in the C++03 Standard:

1.9p16: There is a sequence point at the completion of each full-expression.

A statement is the simplest kind of "full-expression", but the Standard is worded to include other expressions that are not technically part of any statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM