i have object has different constructors. want add constructor based on arbitrary data try process data , call correct constructor.
afaik there 2 ways it:
static function returns created object
static *a from_data(/arbitrary data/);
create private "init" function called constructors
but wondering problems , potential pitfalls of using placement new on using desired constructor. code be:
#include <new> struct { /*different constructors*/ a(int i) {}; a(double d) {}; a(/*large set of data*/) { /*large set of data gets processed , depending on processing different constructor gets called*/ this->~a(); //deletes current object if (true) { new (this) a(1); //reconstructs object calling correct constructor data } else { new (this) a(1.0); //reconstructs object calling correct constructor data } }; }; int main(int argc, char* argv[]) { a; }
you want compile time decision (choice of constructor delegate to) run-time information (result of processing data set).
that means directly want, cannot done.
but can use idea of static
member function returns created object, except instead of a*
should return a
, or else smart pointer.
re other suggested solution,
” create private "init" function called cosntructors
… doesn't solve stated problem, , it's bad idea.
re
” problems , potential pitfalls of using placement new on
well, it's not code can rely on. believe it's undefined behavior because @ point object self-destroys it's not initialized. if should turn out it's technically defined case @ hand, it's not code want rely on. , in setting possible maintenance, stumbling on code have replace rather wasting time trying prove ub or not. no™ dark corners of language.
Comments
Post a Comment