operator ++()nothrow不编译

时间:2016-05-17 00:20:49

标签: c++ nothrow

为什么我不能使operator ++()nothrow?

这可能是使用postfix ++运算符(通过前缀++运算符)的几个优点之一。

例如,此代码无法编译

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;
};

另外注意,后缀运算符也可以是线程安全的。

1 个答案:

答案 0 :(得分:6)

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

我认为你想要的是noexcept