Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

new(nothrow)

31 views
Skip to first unread message

gdo...@gmail.com

unread,
Dec 24, 2022, 9:27:48 PM12/24/22
to
is it best practice to use new(nothrow) as to not have to handle the exception?

Öö Tiib

unread,
Dec 24, 2022, 10:54:08 PM12/24/22
to
On Sunday, 25 December 2022 at 04:27:48 UTC+2, gdo...@gmail.com wrote:
> is it best practice to use new(nothrow) as to not have to handle the exception?

Best practice is not to use explicit new but standard library containers.
Standard library does not use new(nothrow).

Do you have some plan what to do when allocation fails somewhere?
If no then you can just catch std::bad_alloc in main and then report that
program died because it is out of memory. If yes then you can catch at
points where it is easiest to switch to that plan.
With new(nothrow) you will have to check in code after every new.
Check that has no idea what to do if it failed or how far it is from
place where there is something to do. How is it better?

Also the exceptions that are likely never thrown typically cost lot less
performance than those checks all over code base.

Paavo Helde

unread,
Dec 25, 2022, 3:30:56 AM12/25/22
to
25.12.2022 04:27 gdo...@gmail.com kirjutas:
> is it best practice to use new(nothrow) as to not have to handle the exception?

No, because then you would handle the nullptr return, which becomes more
cumbersome as soon as you have to do that in more than one place.

Best practice is to figure out if and why are you wanting to do a
dynamic allocation in the first place, then use std::make_unique or
std::make_shared as appropriate.


Andrey Tarasevich

unread,
Dec 25, 2022, 4:09:28 AM12/25/22
to
On 12/24/2022 6:27 PM, gdo...@gmail.com wrote:
> is it best practice to use new(nothrow) as to not have to handle the exception?

Do you have a good strategy for handling a null return?

If you do, then just go ahead and use 'new(nothrow)' if you like it better.

If you don't, then it makes no difference. Better use plain 'new', since
it looks cleaner.

--
Best regards,
Andrey
0 new messages