Re: Is it correct? Two same named classes in different unnamed
namespace get same typeid
On Jul 31, 1:32 pm, Qi <n...@no.com> wrote:
Let me show sample code to explain,
Source file a.cpp (not header)
const std::type_info & getA()
Source file b.cpp (not header)
class TestClass // same name as above class
// differ with another TestClass, so the type should be differ
const std::type_info & getB()
Tested in GCC 4.4.0 and 4.5.2, calling getA and getB, the
result is exactly same (== will return true).
So seems the RTTI for two TestClass are same.
That surprises me very much. The two TestClass are two
different classes, because they are in two different namespaces.
(I don't have g++ installed on this machine to verify, but I do
remember doing some experiments with the uniqueness of
typeid(x).name(), and g++ generated different names for the two
How did you do your tests?
I also tested in VC 2008, the typeid for both TestClass
are different, which is I expected.
However, seems previous VC also had that bug,http://connect.microsoft.com/VisualStudio/feedback/details/100472/wro...
Is it standard behavior, or undefined behavior, or a bug in GCC?
Given that both classes are in an unnamed namespace, and they
are in different source files, they are unrelated classes, and
getA() may not be equal to getB().
If the classes weren't in unnamed namespace, you would have undefined
behavior (a violation of the one definition rule).
A further question:
Is it safe to use type_info to distinguish types?
i.e, different types (no matter in which namespace, which file),
will give different type_info?
Yes, although it's rarely useful.
The behavior in GCC really made me doubt that.
I'd want to see a copy/paste of the code, for all three files
(including the file with main which called getA() and getB()),
and the command line used to compile them, before I accept that
g++ is getting something this fundamental messed up. Especially
as I have seen g++ returning different values when calling
type_info::name in such cases.