I have two questions about the new operator:
-
Can the new operator fail to allocate memory?
-
Should one test after every use of new, if there really was an object created?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
operator new throws a std::bad_alloc exception on failure, unless you’re explicitly using the
nothrowversion. Therefore, don’t check the return value: If you arrive at the next line after the constructor call, you can safely assume that the constructor succeeded.But do wrap the appropriately-scoped branch of your code in a try-catch block: Usually not right directly around the new call, but somewhere up the line where you can call off everything that depends on the allocation, and nothing else.
UPDATE: But see also Jonathan Leffler’s comment below about the nothrow variant of new.