why the RTTI cannot tell the const qualifier of variables

Z

Zeng Dinghao

char c = 'd';
const char cc = 'd';
char* pc = "dfdfdf";
const char* pcc = "dfdfdf";
char const* cpc = "dfdf";

cout << typeid(c).name() << endl;
cout << typeid(cc).name() << endl;
cout << typeid(pc).name() << endl;
cout << typeid(pcc).name() << endl;
cout << typeid(cpc).name() << endl;

in vc6, I got

char
char
char *
char const *
char const *

and in gcc, I got

c
c
Pc
PKc
PKc
 
R

Ron Natalie

Zeng said:
char c = 'd';
const char cc = 'd';
char* pc = "dfdfdf";
const char* pcc = "dfdfdf";
char const* cpc = "dfdf";

cout << typeid(c).name() << endl;
cout << typeid(cc).name() << endl;
cout << typeid(pc).name() << endl;
cout << typeid(pcc).name() << endl;
cout << typeid(cpc).name() << endl;

in vc6, I got

char
char
char *
char const *
char const *

This is the expected result. The C++ standard explicitly
says:

The top-level cv-qualifiers of the lvalue expression or the type-id that is the
operand of typeid are always
ignored. [Example:
class D { ... };
D d1;
const D d2;
typeid(d1) == typeid(d2); // yields true
typeid(D) == typeid(const D); // yields true
typeid(D) == typeid(d2); // yields true
typeid(D) == typeid(const D&); // yields true
—end example]

There are practical reasons for this. top-level constness is a
rather fleeting thing.
 
R

Ron Natalie

Ron said:
typeid(D) == typeid(const D&); // yields true
—end example]
Ooops...this is either wrong or the standard is....better
go call this one up in comp.std.c++.
 
A

Andrey Tarasevich

Zeng said:
char c = 'd';
const char cc = 'd';
char* pc = "dfdfdf";
const char* pcc = "dfdfdf";
char const* cpc = "dfdf";
...
Subject: why the RTTI cannot tell the const qualifier of variables

Because 'typeid' does not work with types of variables. 'typeid' works
with types of expression results.

In C++ language const-qualification is not applicable to rvalues of
non-class type. Such rvalues are neither const nor non-const, they are
simply rvalues. For example, the result of the expression 'cc' is an
rvalue of type 'char' (not 'const char').

For this reason, if you apply 'typeid' to an expression, which returns
an rvalue of non-class type, you'll never see any traces of
const-qualification in the result of 'typeid'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,524
Latest member
ecomwebdesign

Latest Threads

Top