chances are, you'll open thousands. If the file is a couple of megs,
you won't get there.
But if the file size is unknown until say a user selects from a dailog
window.
You can't predict how many buffers and what size each buffer will need
to be.
The only way this system can really work is if you grab a memory pool
and then have some kind of allocation handler that processes
allocation/deallocation from the pool.
I don't know how you would know the size of this pool to initially
grab. Perhaps a trial and error until a bad alloc is thrown . :)
Sorry, I poorly explained myself there. I was arguing with something
that wasn't written.
What I wanted to say is that the number of windows you'll get to open
will vary wildly depending on the file size. I agree that one you
can't predict anything.
Therefore, the best (and simplest if you ask me) way to proceed is to
try to allocate and do __not__ "handle" bad_alloc. I pretty much agree
with Skutt that "handling" OOM is impossible, especially not at the
spot where it occurred, because memory is possibly tightest there. In
the imaginary editor, imagine sequence of events:
ask the user which file to open
create "frame" window for the file
create, I dunno, borders, toolbar, whatever
create widget to host text
load the text (say, whole file into a buffer that you pass to the
widget for display)
In pseudo-C++, that might be:
auto_ptr<Frame> openFile(const char* name)
{
auto_ptr<Frame> frame = new Frame();
frame->Decorate();
EditorWidget& e = frame->GetEditor();
vector<char> text = LoadFile(name);
e.SetText(text);
}
In the above, you allocate all sorts of stuff: frame, "decorations",
editor widget inside the frame. (I presume that frame "owns" that, and
GetEditor creates actual EditorWidget e.g. on demand, therefore it
gives it out as a reference). I also presume that LoadFile is a
function that loads a file into vector<char>. I presume that any
function you see throw an exception in case of any problems.
I say that the above code is resilient to resource shortage, and that,
if there is a resource shortage at any point bar "new Frame()" line,
it will nicely clean up behind and leave with at least some resources.
You can call this as much as you like and you'll be fine. No arena
allocators, no pools, no try/catch, no nothing. I further say that C++
makes it +/- easy to write similarly correct code.
Finally, I say: boy did I go off the tangent here...
windows. Display a message to user and say no more windows until you