c++ - Catching exceptions for specific base members during construction -
i'm aware, given class foo
base class base
can write
foo(/*real code has parameters here*/) try : base(), /*real code has parameters here*/ anothermember(somefunction(/*some parameters here*/)) { } catch (...){ }
but there syntax can use put try
catch
block around anothermember
opposed entire base member list , constructor body?
(note anothermember
const
type needs in initialiser list)
doing doesn't quite make sense anothermember
initialises function put try..catch
in function. i'm assuming has copy-constructor doesn't throw , 1 might throw takes parameters , somefunction
invokes one.
what want if anothermember
fails construct properly?
your obvious alternative wrap anothermember
in kind of smart-pointer, possibly making "nullable" if failed initialise. if created own special object contain message of exception thrown .
struct anothertypewrapper { std::unique_ptr< anothertype > ptr; std::string errormsg; anothertypewrapper( args&& args... ) // ok not variadic { try { ptr.reset( new anothertype( std::forward(args) ) ); // or whatever syntax } catch( std::exception const& err ) { errormsg = err.what(); } } };
something that.
Comments
Post a Comment