initialization - C++ Declare const variable, but postpone its initialisation? -


context:

a function (from api cannot modify) returns constant reference object objectregistry:

const foo& f(args) 

i need obtain constant foo object, require different instance of foo based on conditional.

naievely, i'd first declare f returns, , call f initialise variable foo.

const foo& foo; // declare if( == true ){     foo = f(arg1); // initialise }else{     foo = f(arg2); // initialise } // guaranteedly initialised in line 

this not work, first (i assume) call constructor empty argument. afterwards have const object cannot overwrite. rather, compiler complains: error: 'foo' declared reference not initialized. same problem occurs if foo declared const foo foo;

the following work.

const foo* fooptr; if( == true ){     fooptr = &f(1); }else{     fooptr = &f(2); } const foo& foo = *fooptr; 

questions:

  • are there issues method, other being ugly (imo)?
  • are there nicer ways same end?

somewhat related topics:

you use wrapper

const foo& getfoowrapper(something) {  // assume returning ref fine,                                              if (something) return f(1);        // because f returns const&     else           return f(2); } 

and simply

const foo& foo = getfoowrapper(); 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -