operator++() nothrow 不编译

operator++() nothrow does not compile

为什么我不能让 operator++() 不抛出?

这可能是使用后缀 ++ 运算符(相对于前缀 ++ 运算符)的少数优势之一。

例如,这段代码无法编译

class Number
{
public:
    Number& operator++ ()     // ++ prefix
    {
        ++m_c;
        return *this;
    }

    Number operator++ (int) nothrow  // postfix ++
    {
        Number result(*this);   // make a copy for result
        ++(*this);              // Now use the prefix version to do the work
        return result;          // return the copy (the old) value.
    }

    int m_c;
};

附带说明一下,后缀运算符也可以是线程安全的。

nothrow 是一个常量,用于传递给 operator new 以指示 new 不应在出错时抛出异常。

我想你想要的是noexcept