by ghosty141 · 4y ago · 0 comments
Constructors are simply not meant to fail. You should never do something like io in a constructor. For everything more complicated than setting some fields a factory is better suited.
std::fstream s(filename);
if (!s.is_open()) {
std::cout << "failed to open " << filename << '\n';
}
No one should ever have to use factories, they really suck. Too much boilerplate, too much code duplication.How would you reconcile that with the fact that std::vector<T>::vector() is explicitly permitted to fail? [1] Do you construct your std::vector<T> objects with factories too?
> Exceptions: Calls to Allocator::allocate may throw.
[1] https://en.cppreference.com/w/cpp/container/vector/vector
I usually do it like that:
try
{
vec.resize( wantedSize );
}
catch( const std::bad_alloc& )
{
return E_OUTOFMEMORY;
}Yeah, but that thing has more than one constructor. Since C++/17, the default constructor of std::vector which doesn’t allocate any storage is usually marked as noexcept, i.e. the standard does not allow it to throw anything. This feature allows to make classes which contain vectors yet don’t throw exceptions from constructors.
P.S. The move constructor of std::vector is marked with noexcept as well, i.e. it’s even possible to construct non-empty vectors without any exceptions.