1

Why can't I make operator++() nothrow?

This could be one of the few advantages of using the postfix ++ operator (over the prefix ++ operator).

For example, this code does not compile

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

On a side note it the postfix operator could also be made thread-safe.

Damian
  • 4,395
  • 4
  • 39
  • 67
  • 1
    Is there a reason you're not declaring the prefix operator `nothrow`? It would help to know what the compiler is complaining about, but I figure it could be a simple as a `nothrow` postfix operator complaining when you use a non-`nothrow` prefix operator to implement it. – ShadowRanger May 17 '16 at 00:23
  • @ShadowRanger: That's it exactly. `nothrow` functions can't call potentially throwing functions. – Mooing Duck May 17 '16 at 00:24
  • In VC 2015 I get: error C3646: 'nothrow': unknown override specifier – Damian May 17 '16 at 00:32

1 Answers1

6

nothrow is a constant used to pass to operator new to indicate that new should not throw an exception on error.

I think what you want is noexcept.

zdan
  • 28,667
  • 7
  • 60
  • 71
  • A bit strange why we need two keywords in C++ they seem similar to me. – Damian May 17 '16 at 00:36
  • @Damian `nothrow` is not a keyword in C++, it's a constant of type `std::nothrow_t`. – Baum mit Augen May 17 '16 at 00:41
  • technically nothrow is not a keyword. It's a constant in the std namespace. But I agree, it is confusing (even the commenters on your question were confused). – zdan May 17 '16 at 00:42
  • @Damian that's because nothrow was there even before the idea of noexcept. You can't change the meaning of an existing entity because of the havoc it will create. C++ is not python. The committee continues to carry the burden of backward compatibility. – bashrc May 17 '16 at 00:43