The question is simple. Why does this compile:
bool b(true);
if (b) { /* */ }
And this compile:
if (bool b = true) { /* */ }
But not this:
if (bool b(true)) { /* */ }
In my real code, I need to construct an object and test it, while also having it destroyed when the if-block ends. Basically, I'm looking for something like this:
{
Dingus dingus(another_dingus);
if (dingus) {
// ...
}
}
Of course, this would work:
if (Dingus dingus = another_dingus) { /* */ }
But then I'm constructing a Dingus
and calling operator=
on it. It seems logical to me that I would be able to construct the object using whatever constructor I please.
But I'm baffled why this isn't grammatically correct. I've tested with G++ and MSVC++ and they both complain about this construct, so I'm sure it's part of the spec but I'm curious as to the reasoning for this and what non-ugly workarounds there may be.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…