An STL algorithm should not make such guarantees. Tools should not instruct their master.
The
std::copy() algorithm is guaranteed not to
throw only if the three iterators given to it are guaranteed not to
throw. Notice how this implies a lot about the iterators and the containers themselves...
Frankly, if
new or
malloc() fail, your entire system is unstable and about to crash. Likewise, if your OS throws an exception it will crash your program anyway. But, that aside, why not keep
everything you want protected in
try..
catch blocks? And why mess with a temporary anyway?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
...
template <typename T>
bool X::load( const std::string& filename )
{
try
{
ifstream file( filename );
std::copy(
std::istream_iterator <T> ( file ),
std::istream_iterator <T> (),
std::back_inserter( vt )
);
bool result = file.fail();
file.close();
return result;
}
catch (...)
{
return false;
}
}
| |
This appends as many
Ts as it can get from the file to
vt and returns whether or not something went wrong (including if the file could not be opened).
If you really, really want
vt to be guaranteed to have the same value if anything does go wrong, you can always
std::streamsize original_size = vt.size();
at the beginning of your function and
vt.erase( vt.begin() + original_size );
on failure.
Since
everything is inside a catch-all
try..
catch construct, you can safely add a zero-throw list specifier to the header:
1 2
|
template <typename T>
void X::load( const std::string& filename ) throw()
| |
Hope this helps.