Re: Avoiding the anonymous variable declaration RAII error...
Greg Herlihy ha scritto:
So, would you expect the Visual Studio 2005 C++ compiler to compile
this program successfully:
struct Mutex
{};
struct Locker
{
Locker(const Mutex&) {}
};
typedef Locker StLocker;
Mutex m_mutex;
int main()
{
StLocker (m_mutex); // ?? OK or Error?
}
In fact no version (6, 7, or 8) of the Visual Studio C++ compiler, nor
the gcc, Comeau, or EDG C++ compilers will successfully compile the
above program. And in each case, the C++ compiler reports the same
error:
Error: 'Locker' : no appropriate default constructor available
According to this error message, a C++ compiler interprets this
declaration:
StLocker (m_mutex)
as the equivalent to this declaration:
Locker m_mutex;
I tried VC7.1 and Comeau and they report the same error message even if
you replace the line
StLocker (m_mutex); // ?? OK or Error?
with:
Locker (m_mutex); // ?? OK or Error?
In this respect, using the class name or the typedef name makes
absolutely no difference.
In both cases, the program is declaring (and default-constructing) a
Locker object named "m_mutex" - and in neither case is the program
initializing an unnamed Locker object with a Mutex variable named
"m_mutex". So the difference between using a typedef name and the
equivalent class name in this context - has a dramatic effect on the
declaration's meaning.
In this context, the use of the typedef has no "dramatic" effect.. it
has no effect at all.
So, unless Locker's Mutex initializer is in fact optional, the fact
that your program allows Locker class to be default-constructed - is a
serious flaw in Locker's implementation; especially since a typedef
name can - as shown above - easily conceal the fact that a particular
Locker object is being default-constructed.
Sure having the Locker class default-constructible is a design flaw.
However, it's a flaw which cannot be concealed using a typedef. By the
way, your example above did not provide any evidence that a typedef
could actually conceal anything.
I wouldn't expect it to: a typedef doesn't introduce
a new type, it's just a synonym.
Your premise does not support your conclusion. The fact that a typedef
name does not name a type in its own right (like a class name does) -
is exactly the reason why a typedef name does not behave exactly like
a class name in every context.
Please list the contexts where a typedef name behaves differently from
the class name it refers to. 7.1.3/4 "A typedef-name that names a class
is a class-name (9.1)." makes it very difficult to me to imagine any
such context, but apparently you know otherwise...
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]