
Eric Niebler wrote:
AlisdairM wrote:
int a = 13; int &b = a; int c = 42;
optional< int & > d = b; d = c;
<snip>
For the curious, the current answer is option 3 - d rebinds a reference to c.
Ha, very interesting experiment!! I agree the semantics are subtle, I aways did. Yet the as I've been trying to explain the alternative is even more subtle. I wonder what would be the result of the following thought experiment: Please, answer the questions _without_ looking at the answers, and if possible post your initial results; then compare with the answers. int a = 1; int b = 2 ; int c = 3 ; int &ra = a; int &rb = b; int &rc = c; optional<int&> o = ra; o = rb ; // [1] o = none ; o = rc ; [2] (a) What is the value of 'a' after [1]? (b) What is the value of 'a' after [2]? ANSWERS: If no-rebinding is used, the answers are: (a) 2 (b) 2 // Is not '3' because 'a' is "released" at 'o=none' If rebinding is used: (a) 1 // Is not '2' because 'a' is never changed (b) 1 // Is not '3' because 'a' is never changed
Huh. IANAOU* but this seems surprising to me. I would expect this not to rebind the reference. Had I wanted that behavior, I would have used an int*
Would you be able to use int* then you probably should. optional<int> is intended to allow you to express an absent 'int' without resorting to a pointer. (and please!, this doesn't mean at all that optional is a pointer... both optional<> and pointers are models of a more fundamental concept: OptionalPointee or Nullable) Best -- Fernando Cacciola SciSoft http://fcacciola.50webs.com/