【问题标题】:c++: invalid initialization of reference of type 'const int*&' from expression of type 'int*'c ++:从类型'int *'的表达式中对类型'const int *&'的引用的无效初始化
【发布时间】:2017-01-26 13:39:12
【问题描述】:
int *b = new int();
const int *&a = b;

IDE 显示“来自 int* 类型的表达式的 const int*& 类型的引用无效初始化”

我不明白。

【问题讨论】:

  • 就指针而言,原因是explained here。请考虑以下情况:const int i = 0; int *p; const int *&z = &p; z = &i; - p 不能指向 i。但是,如果允许这种转换,那么您可以通过引用更改p 指向i 并使用它来更改i

标签: c++ pointers reference initialization


【解决方案1】:

你不能绑定不同类型的引用;在这种情况下,它们是 int *const int*

对于const int *&a = b;b 是一个int*,然后首先需要转换为const int*。这里允许隐式转换,但转换后的const int*是临时的,不能绑定a;因为它是对非常量的左值引用。

另一方面,temporary object 可以绑定到左值引用到 const 或右值引用,即

const int * const &a = b; // fine, and the lifetime of the temporary is extended to match the lifetime of the reference a

注意const 的位置,现在a 被声明为指向 const int 的 const 指针的左值引用。

【讨论】:

    【解决方案2】:
    • b 是一个指向 int 的指针
    • a 是对指向 const int 的指针的引用。

    所以b 不能分配给a

    您可能希望引用一个 const 指向 int 的指针

    int *b = new int();
    int *const &a = b;
    

    【讨论】:

      【解决方案3】:

      正式的原因是int*const int*是不同的类型,转换会创建一个临时的,不能绑定一个非常量引用到一个临时的。

      使它成为对 const 指针的引用会起作用:

      const int * const &a = b;
      

      举个励志的例子,让我们假设这是允许的:

      int* p = nullptr;
      const int*& rp = p;
      

      rpp 现在指向同一个对象。

      让我们创建一个const int

      const int y = 1;
      

      const int* 分配给const int* 应该是安全的,对吧?

      rp = &y;          
      

      现在,由于 *p 不是 const,我们可以为其分配一个新值:

      *p = 0xbaad1dea;  
      

      但是prp是同一个对象,而*rpy所以*p也是y,而yconst

      现在我们处于未定义行为的领域。

      【讨论】:

        【解决方案4】:

        问题在于这两种类型

        int *
        

        const int *
        

        是两种不同的类型。因此,右侧的变量b 的表达式被转换为rvalue 类型的const int *

        您不能将非常量引用绑定到rvalue。所以你必须写

        const int * const &a = b;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-07
          • 2021-10-26
          • 1970-01-01
          • 2022-01-08
          • 1970-01-01
          相关资源
          最近更新 更多