Re: Is this valid and moral C++?
"Roland Pibinger" <rpbg123@yahoo.com> wrote in message
news:46056dba.2463312@news.utanet.at...
: On 24 Mar 2007 08:04:48 -0700, "werasm" wrote:
: >> Yes, this is one of several ways to address the problem.
: >> All I am saying is that this issue is worth attention.
: >>
: >Yes, I cannot understand Roland's point too. Obviously reserve might
: >solve the problem. I think it could cause unnecessary memory
: >allocation though.
:
: OOM can be handled by a global new_handler if the operating system
: supports it. Linux e.g. uses 'optimistic memory allocation' so
: checking for OOM exceptions is not useful there. See also Moral #2
: here: http://www.gotw.ca/publications/mill16.htm
I rarely check for new/memory allocations in my code. I only do my
best to write code that is exception-safe. New-ing an object can
fail in any case because of a constructor failure.
Given, push_back of a pointer is unlikely to fail, yet formally
it is a container operation that is allowed to fail and throw
an exception. So I'll write my code "to the spec".
: >I would prefer:
: >
: >std::auto_ptr<Object> instance( new Object );
: >myVector.push_back( instance.get() ); //X
: >instance.release(); //No X
:
: This is impractical for any real-world program.
Indeed. The real issue is that it is illegal to create a
container of auto_ptr. vector<T*> is brittle by nature.
When I have a container of polymorphic objects, I find
that the overhead of vector< shared_ptr<T> > is acceptable.
When not using polymorphic objects, I do not use containers
of pointers, but a container of <T> - with possibly some
accessory "index" containers storing pointers that refer
into an "allocation" container (a list or deque).
In C++0x, with the introduction of R-value references, I expect
that an equivalent of vector< auto_ptr<T> > will become available
in the standard library.
: In general you need
: not check within your program for OOM, stack overflow, int overflow,
: etc.. You can reasonably assume that you are in 'secure territory'
I write software for medical devices.
You think that one can just assume that int overflows never happen?
void on_decrement_radiation_power()
{
--ray_power; // safe? what if unsigned ray_power was zero?
}
Depending on the type of device your code runs on, you will also
ensure that stack overflows can't be triggered by excessive
recursion, or ensure graceful failure if sufficient memory
isn't available for new incoming data.
Cheers -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form