如何使类型别名"a pointer to an array of const int"?

How to make type alias to "a pointer to an array of const int"?

本文关键字:of array const int an pointer 类型 何使 别名 to      更新时间:2023-10-16

我正在做关于类型别名的练习(ex3.44 c++ Primer 5th)。下面的代码将使:

  1. 指向const int类型数组的指针的类型别名,

  2. const int数组引用的类型别名

然而,结果不符合预期(见注释)。为什么?

int main(){
  int ia[3] = {0, 1, 2};
  typedef const int (*cpa)[3];
  cpa g = 0;                    //(gdb) ptype g: type = int (*)[3]
  typedef const int (&cra)[3];
  cra h = ia;                   //(gdb) ptype h: type = int (&)[3]
  return 0;
}

当我删除数组时,它按预期工作。参见下面的代码:

int main(){
  int i = 42;
  typedef const int* cp;
  cp e = &i;                    //(gdb) ptype e: type = const int *
  typedef const int& cr;
  cr f = i;                     //(gdb) ptype f: type = const int &
  return 0;
}

最后一件事,如果使用"using"关键字,如何重写别名定义?

这只是省略了constgdb版本的输出。const仍然很重要。我们可以用下面这个无法编译的程序来证明:

int main(){
  const int ia[3] = {0, 1, 2};
  typedef int (*cpa)[3];
  cpa g = 0;
  typedef int (&cra)[3];
  cra h = ia;
  return 0;
}

对于我来说,使用gdb 7.7,输出如预期:

(gdb) ptype g
type = const int (*)[3]
(gdb) ptype h
type = const int (&)[3]

using重写这些typedef s:

using cpa = const int (*)[3];
using cra = const int (&)[3];

您可以看到模式只是using identifier =后面跟着缺少标识符的声明。

你太相信gdb了。它省略了"const",原因我不明白。您应该用其他方法验证类型的正确性。一种方法是赋值给g[0]。这将给您一个错误,其中包含如下消息:

error: incompatible types in assignment of ‘int’ to ‘const int [3]’

马上告诉你你的问题不存在。

还可以使用typeid从编译器获取类型并打印出来。在vc++中,这样做很简单。使用gcc时,您需要调整结果以使其可读。下面的代码输出g和g2的类型,带const和不带const。

#include <stdio.h>
#include <typeinfo>
#ifdef __GNUG__
#define DEMANGLE
#endif
#ifdef DEMANGLE
#include <cxxabi.h>
#endif
template <typename T>
const char* TypeName(const T& type)
{
#ifdef DEMANGLE
    int status = 0;
    // Convert the cryptic gcc name decorations to something
    // human readable.
    return abi::__cxa_demangle(typeid(type).name(), NULL, NULL, &status);
#else
    return typeid(type).name();
#endif
}
int main(){
  int ia[3] = {0, 1, 2};
  typedef const int (*cpa)[3];
  cpa g = 0;                    //(gdb) ptype g: type = int (*)[3]
  typedef int (*cpa2)[3];
  cpa2 g2 = 0;                    //(gdb) ptype g: type = int (*)[3]
  typedef const int (&cra)[3];
  cra h = ia;                   //(gdb) ptype h: type = int (&)[3]
  printf("Type of 'g' is '%s'n", TypeName(g));
  printf("Type of 'g2' is '%s'n", TypeName(g2));
  //g[0] = 2; This fails to compile, thus proving that cpa/g have the correct type.
  return 0;
}