Calling object constructors without using new

Started by
11 comments, last by Khatharr 11 years, 4 months ago

Trivial accessors and mutators are wasted code.

Also, two-phase construction is usually a massive anti-pattern.

You should always create your objects in a sane state, and always maintain that sanity by upholding class invariants. Use of trivial mutators means you have violated encapsulation in most cases, and use of two-phase construction is fundamentally counter to this goal in and of itself.


(There are times when two-phase construction is acceptable. This is not one of them.)

Kind of you, much to learn i have.
Advertisement

Typically I only try to catch std::bad_alloc and return an error code from the offending function. Other exceptions I'm leaving unhandled for now, though I may place a try/catch in my main at a later point just to pop an error message.

I may actually switch to just disabling exceptions since I honestly preferred it when allocators returned NULL instead of throwing. I guess I'll think about it some more.

I feel bound to ask why. I don't think I have ever experienced legitimately running into std::bad_alloc. For me it only ever happened as a side effect of a bug that really should be dealt with directly or trying to process a huge dataset not as out-of-core as it was planned to be.
I don't really understand returning an error code either. If something goes wrong because no more continuous memory is available then the most sensible thing to do is A) giving up, because this machine does not seem to have to resources we need, or B) catching the exception at a sensible location and calling as many "clear your caches NOW" as possible. Sure, I can do that with an error code but why should I bother propagating that up the callstack if the exception can do exactly that automatically?
Mobile phones and other embedded devices might be something else but in my (admittedly limited) experience they seem to prefer telling you in some other way if you start getting too memory-greedy for them and even then an std::bad_alloc should not really happen.

Edit: and if you really want a non-throwing behavior from new, why don't you use std::nothrow?
As for what you mentioned about memory recovery that's why I'm considering it rather than having already done it.

As for nothrow - and this is the best reason ever (only half sarcastic here) - I don't like the syntax.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

This topic is closed to new replies.

Advertisement