C++11言語仕様ではif/for/while/do-while構文における条件部(condition)の扱いが微妙に変更された。また、これに関連してC++標準ライブラリのインタフェースも一部変更されている。(→[id:yohhoy:20120406:p1]など)
この仕様変更により、C++98/03におけるSafe bool Idiom*1はC++11では時代遅れとなる。C++11では明示的ユーザ定義変換関数 explicit operator bool() const;
を定義しておけば良い。
C++03、C++11(N3337) 6.4/p4よりそれぞれ該当箇所を引用(下線部は強調)。
The value of a condition that is an initialized declaration in a statement other than a
switch
statement is the value of the declared variable implicitly converted to typebool
. If that conversion is ill-formed, the program is ill-formed.
The value of a condition that is an initialized declaration in a statement other than a
switch
statement is the value of the declared variable contextually converted tobool
(Clause 4). If that conversion is ill-formed, the program is ill-formed.
"implicitly converted to"と"contextually converted to"の違いは下記の通り。(N3337 4/p3より引用&整形)
- An expression
e
can be implicitly converted to a typeT
if and only if the declarationT t=e;
is well-formed, for some invented temporary variablet
(8.5).- Certain language constructs require that an expression be converted to a Boolean value. An expression
e
appearing in such a context is said to be contextually converted tobool
and is well-formed if and only if the declarationbool t(e);
is well-formed, for some invented temporary variablet
(8.5).
関連URL