使用类型别名从“const T*”到“T*”的无效转换

问题描述 投票:0回答:1

我正在使用

pointer
const pointer
的类型别名,我不明白为什么返回
cost pointer
const_pointer
之间存在差异。

我认为

const pointer
在这种情况下相当于
const int*
,但我收到无效的转换编译错误:
error: invalid conversion from 'const int*' to 'S::pointer {aka int*}

struct S
{
  using pointer = int*;
  using const_pointer = const int*;

  // const_pointer get() const { return &i; }    // OK
  const pointer get() const { return &i; } // ERROR

  int i = {};
};

int main()
{
  const S s;
  s.get();
}
c++ compiler-errors
1个回答
0
投票

我发现如果你不再把

const
放在左边会有帮助。如果我重新表述你的问题:

struct S
{
  using pointer = int*;
  using const_pointer = int const*;
  using pointer_const = int*const;

  // const_pointer get() const { return &i; }    // OK
  // pointer_const get() const { return &i; }    // ERROR
  pointer const get() const { return &i; } // ERROR

  int i = {};
};

int main()
{
  const S s;
  s.get();
}

我已将

const int*
替换为
int const*
。作为 C++ 中的一般规则,类型中的
const
适用于类型中 left 上的组件。只有当左边没有类型时才违反这个规则。

当左侧没有组件时,它会查看该类型的局部表达式 - 其中添加

const
。它向右移动一步,并遵循左侧应用规则。所以:

const pointer

成为

pointer const 

那就变成了

int*const

不是

int const*

第二部分是理解“指向 const int 的指针”与“指向非 const int 的 const 指针”不同。在一种情况下,我们指向的是我们无法修改的东西;另一方面,我们无法确定我们指向哪个对象,但我们可以修改该对象。

© www.soinside.com 2019 - 2024. All rights reserved.