Re: Inconsistent behaviour for certain conditional expressions
The example I concocted was for illustration only.
The place where using this kind of construct is useful is when doing a
type of RAiI (Resource Aquisition is Initialization):
class Lock
{
Resource& r;
operator bool();
~Lock(){r.Release();}
};
class Resource
{
void Release();
Lock Acquire();
};
Now, normally you would write code like this:
Resource r;
const Lock l = r.Aquire();
if (l)
{
etc....
}
The problem is that the Lock l variable is in the scope outside the
conditional block. This means that you can't make the automatic
destructor call free the resource at the end of the conditional block.
Now observe this code:
if (const Lock l = r.Aquire())
{
}
Not only is the code smaller, the lock only exists in the scope of the
conditional block.
What I had in my older code was a expression that looked like:
if (const Lock l(r))....
which I think is better looking and avoids the problematic style of
using the the assignment operator in a conditional expression (the
classic error of writing a=b, instead of a==b)
If somebody can suggest a more elegant way of doing RAiI than the one I
illustrated above, I am all ears.
thanks.
Tom Serface wrote:
There are a number of new issues that make VC++ 2005 more "compliant". For
better or worse at least now it works as it should for the most part (which
isn't so much the way we like it ... or how it used to work) This article
may be of interest:
http://www.developer.com/net/cplus/article.php/3493706
I think you found one they didn't list though. FWIW, I think doing
initializations like this in an "if" statement are a bad idea anyway.
Perhaps in a "for" statement it would make more sense, but your example here
seems to make the if statement kind of irrelavent since int i = 1.
Tom
"redblue" <redqil@gmail.com> wrote in message
news:1155139110.947391.196900@m79g2000cwm.googlegroups.com...
Look at the following two expressions:
1. if(int i=1) ...
2. if(int i(1)) ...
msvc6 has no issues with them but vc2005 chokes on #2. I always thought
the two forms of variable initialization are identical. Am I missing
something?
thanks.