3 ms·
To add to "Let’s say I want to know if a constructor failed." Constructors are simply not meant to fail. You should never do something like io in a constructor
by ghosty141 5y ago
To add to "Let’s say I want to know if a constructor failed."
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.
- nmilo 5y agoWhy? Isn't one of the ideas of C++ that every constructed object is in a valid state? Even the STL has constructors that can fail, and it does it through member variables/flags, which doesn't seem like a very good solution: 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.
- jcelerier 5y agohow do you do non-trivial dynamically-loaded plug-ins without factories ?
- dataflow 5y ago> 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. 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 https://en.cppreference.com/w/cpp/container/vector/vector
- Const-me 5y ago> Do you construct your std::vector<T> objects with factories too? I usually do it like that: try { vec.resize( wantedSize ); } catch( const std::bad_alloc& ) { return E_OUTOFMEMORY; }
- dataflow 5y agoYeah but that's completely avoiding my point. You're claiming constructors aren't supposed to throw, but I'm pointing out the standard explicitly lets vector's constructors fail, and there's no other mechanism to handle that failure than by catching the exception (it's literally designed that way). It's fine if you prefer not to use those constructors in the first place, but that's kind of beside my point about what constructors are "supposed" to do.
- Const-me 5y ago> but I'm pointing out the standard explicitly lets vector's constructors fail 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.
- dataflow 5y agoTry https://en.cppreference.com/w/cpp/container/set/set https://en.cppreference.com/w/cpp/container/set/set