That was my first response when I first saw this code.
However, a colleague of mine has claimed although it is "temporary",
the scope of it belongs to the class instance, NOT the constructor,
hence it is ok.
The collegue is wrong. There are two problems with this code:
-- It binds a temporary to a non-const reference (that is the
effect of the cast). This is illegal, and has been since
something like 1988 or 1989. Still, a lot of compilers
allow it by default. (Sun CC, for example, and I think
VC++, and probably some others.)
-- The lifetime of the temporary ends at the end of the
initialization expression---here, until we return from the
constructor of A. Until the mid-1990's, this was not well
specified, and different compilers behaved differently: g++
destroyed the temporary as soon as it was used (and casting
it counted as a use, so it wouldn't have lasted even into
the call to the constructor of A), CFront based compilers
destructed it at the end of the block (and I don't know when
in this case). Sun CC (which you mention elsewhere that you
use) was originally based on CFront, and even the most
recent versions of the compiler implement the extended
lifetime by default; if you want standard compliance, you
should be specifying something like "-features=tmplife".
(If I were you, I'd check out the -features option for the
version of the compiler you are using. The compiler is very
configurable, and like every other compiler I've used, the
defaults don't correspond to anything I'd want to use.)
I don't know if this is right. (The code has been in
production for years so he must be right though...)
Just because some code happens to work with a particular
compiler doesn't mean it's correct. Especially if that compiler
happens to be designed to support older, non-standard code by
default.
I will try to create a test program to validate.
In any case, I just wanted to know if this is a common programming
tactic by anybody.
I've never seen it before. It is, quite frankly, horrible, and
not conform with modern C++ (where modern means anything since
almost 20 years ago).