问题
Is it the correct behaviour or is it a quirk of g++4.5 that this code prints 1?
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
struct A{};
cout<<(typeid(A)==typeid(const A)&&typeid(A)==typeid(const volatile A)&&typeid(A)==typeid(volatile A));
}
I thought that types differing for cv-qualifiers were threated as very distinct types, even though less cv-qualified types could be implicitly cast to more cv-qualified types.
回答1:
typeid
ignores cv qualifiers, as per the C++ standard (taken from §5.2.8 from ISO/IEC 14882:2003) :
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]
So, the result you're seeing is expected.
回答2:
As @SanderDeDycker mentioned cv qualifiers are ignored. But not for pointers!
example:
#include <iostream>
#include <typeinfo>
int main()
{
int bar = 1;
const int cbar = 10;
volatile int vbar = 10;
const volatile int cvbar = 1000;
int &rbar = bar;
const int &crbar = bar;
volatile int &vrbar = bar;
const volatile int &cvrbar = bar;
int *pbar = &bar;
const int *cpbar = &bar;
volatile int *vpbar = &bar;
const volatile int *cvpbar = &bar;
const volatile int * const cvpcbar = &bar;
const volatile int * const volatile cvpcvbar = &bar;
int&& rrbar = 894354;
const int&& rrcbar = 894354;
std::cout << typeid(bar).name() << '\n';
std::cout << typeid(cbar).name() << '\n';
std::cout << typeid(vbar).name() << '\n';
std::cout << typeid(cvbar).name() << '\n';
std::cout << typeid(rbar).name() << '\n';
std::cout << typeid(crbar).name() << '\n';
std::cout << typeid(vrbar).name() << '\n';
std::cout << typeid(cvrbar).name() << '\n';
std::cout << typeid(pbar).name() << '\n';
std::cout << typeid(cpbar).name() << '\n';
std::cout << typeid(vpbar).name() << '\n';
std::cout << typeid(cvpbar).name() << '\n';
std::cout << typeid(cvpcbar).name() << '\n';
std::cout << typeid(cvpcvbar).name() << '\n';
std::cout << typeid(rrbar).name() << '\n';
std::cout << typeid(rrcbar).name() << '\n';
std::cout << "\n\n";
}
Output
int
int
int
int
int
int
int
int
int * __ptr64
int const * __ptr64
int volatile * __ptr64
int const volatile * __ptr64
int const volatile * __ptr64
int const volatile * __ptr64
int
int
As you can see cv qualifiers are not ignored in the 5 cases involving pointers. Output is the same for MSVS or g++ and C++11, C++14, C++17.
来源:https://stackoverflow.com/questions/10007596/type-info-doesnt-account-for-cv-qualifiers-is-this-right