You can't do this. References must be bound to something, you may not like it but it prevents a whole class of errors, because if you have a reference you can always assume it's bound to something, unlike a pointer which could be null.
Your example code wouldn't work anyway because you attempt to bind a non-const reference to a temporary object, which is invalid.
Why do you need it to be a reference anyway? One solution would be to ensure your type has an inexpensive default constructor and can be efficiently moved, then just do:
Note that both these versions use a const reference, which can bind to a temporary, if the object must be non-const, then again stop trying to use a reference:
MyObject obj = createObject([condition]);
This will probably be just as efficient as what you were trying to do, thanks to the return value optimization
You can use "extern" keyword: first time (assume, in header file) you can declare your variable preceding declaration with "extern" keyword. Later (in source file) you repeat declaration without "extern" and assign value to it.
which is clean and allows using object definition with (possibly different) constructions, a thing you can't do directly with pointers as the compiler will complain from using temporary objects.
I had a similar question, I solved it in a not so smart way.
Question:
I need declare a variable, its type is determined by element of "data"; the variable will be used outside the first if-condition, so it needs to be initialized outside the first if-condition.
wrong code:
Ivar& ref; // invalid, need init
if([condition]){
ref = data["info"];
if (ref.is_dict()) {
...
}
}
string x = ref["aa"];
Use a temp variable in condition
Ivar& ref = dict(); // Ivar and dict are faked; Ivar is interface variable
if([condition]){
Ivar& ref_tmp = data["info"];
if (ref_tmp.is_dict()) { // if the type of temp variable is correct
ref = ref_tmp // assign ref_tmp to ref
...
}
}
string x = ref["aa"];