4

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.

4

2 回答 2

5

typeid根据 C++ 标准(取自 ISO/IEC 14882:2003 的§5.2.8)忽略 cv 限定符:

左值表达式的顶级 cv 限定符或作为 typeid 操作数的 type-id 始终被忽略。[例子:

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

——结束示例]

因此,您看到的结果是预期的。

于 2012-04-04T08:56:55.250 回答
1

正如@SanderDeDycker 提到的 cv 限定符被忽略。但不是为了指针!

例子:

#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";
}

输出

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

如您所见,在涉及指针的 5 种情况下,不会忽略 cv 限定符。MSVS 或 g++ 和 C++11、C++14、C++17 的输出相同。

于 2018-09-25T00:55:58.723 回答