为什么引用的低级常量没有被推导出来?

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

当我们使用

auto 
来推断对象的类型时,顶级
const
会被忽略,例如

const int i = 0; //i is top-level const
auto j = i; //j is an int

但是,低级别的

const
永远不会被忽略,例如

const int * ptr = nullptr //ptr is low-level const;
auto ptr2 = ptr; //ptr2 is also const int*

但是当我定义低级

const
引用并使用
auto
时,它会丢失
const

int var;
const int &ref = var; //ref is low-level const reference
auto ref2 = ref; //ref2 is int&!`

为什么会出现这种行为?

尝试过VS2017 C++编译器

c++ reference constants
1个回答
0
投票
  • const int
    是一个值,复制一个值时不确定你想要它是
    const
    ,所以
    auto
    将被推导为
    int

  • const int*
    这样的指针是不同的东西:如果源是
    const
    ,你不能在它上面放置非常量指针,因为你绕过了它的常量性,因此
    auto
    将不得不保存常量性.

  • 引用在创建后被视为值,因此除非将其指定为

    auto&
    ,否则它将被视为值,并且将是
    int

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