c++exceptionconstructornoexceptnothrow

Does specifying a constructor as noexcept implicitly result in the nothrow version of the new operator being used in C++?


If I specify a constructor as noexcept, does the nothrow version of the new operator implicitly get used when the object is dynamically instantiated?

For example:

class Something {
public:
  Something() noexcept;
};

...

Something *s = new Something;  // <- compiler interprets as "std::nothrow"

I understand that the practical result of using noexcept is that any exception thrown during execution of the function results in std::terminate, I just didn't know if the compiler makes the inference to use nothrow for the construction. My intuition says "no," and that a problem during allocation will result in std::bad_alloc being thrown, and thus result in std::terminate.


Solution

  • The std::bad_alloc exception is for memory allocation, not for the initialization or construction of the object.

    So to answer your question: No, the compiler won't treat that as a no-throw new.