|
Boost : |
From: George A. Heintzelman (georgeh_at_[hidden])
Date: 2001-09-14 12:55:37
> > From: Peter Dimov <pdimov_at_[hidden]>
> > > optional<T> opt;
> > > if(T * pt = opt.get())
> > > {
> > > // initialized, use pt
> > > }
> > > else
> > > {
> > > // not initialized, no pt in scope
> > > }
> The important thing about the idiom is that it checks for initialized
> optional<T> _and_ retrieves a pointer to T at the same time, so - assuming
> that you follow the idiom - you can't access an uninitialized optional by
> mistake (since the pointer is not in scope in the 'else' clause.)
Um, I believe that pt IS in scope, just equal to 0, in the else clause.
gcc seems to agree with me. This code compiles and produces 0x0 as the
output:
#include <iostream>
using namespace std;
int main() {
if (int * x=0) {
cout << *x << endl;
} else {
cout << x << endl;
}
}
This doesn't mean the idiom is bad. You still can't get a non-null
pointer to uninitialized memory, which is good.
George Heintzelman
georgeh_at_[hidden]
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk