【问题标题】:Binding errors in functions with pointer parameters使用指针参数绑定函数中的错误
【发布时间】:2021-09-23 07:27:49
【问题描述】:

以这种方式编写代码时...

#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;

    Node(int data) {
        this->data = data;
    }
};

void display(const Node* &p){
    cout<<p->data<<endl;
}

int main(){
    Node *p = new Node(10);
    display(p);
    return 0;
}

我收到以下错误。

error: cannot bind non-const lvalue reference of type 'const Node*&amp;' to an rvalue of type 'const Node*'

但是,如果将函数 display 的参数 const Node* &amp;p 更改为 Node* &amp;p,则此方法有效。

有人可以向我解释这是如何工作的吗?

【问题讨论】:

  • 为什么还要使用const Node* &amp; 而不是const Node* 或const Node&amp;?您似乎不想修改p 在display 函数中指向的位置。
  • @Zaiborg ,是的,我不想修改指针 p ,它是 display 函数中指向的内存位置。

标签: c++ pointers reference


【解决方案1】:
const Node* &p
// p is a reference to a pointer to a constant 'Node'

而你拥有的是

Node *p
//  ^^ discarding the const qualifier is an error
display(p);
//      ^^ error

可能最简单的解决办法就是兑现承诺

const Node *p = new Node(10);
//^^^
display(p); // OK

void display(const Node*&amp; p) 本质上与

void display(const Node** p)

该标准有一个很好的例子说明为什么不允许使用(非常量)Node** 对其进行初始化(n4659 [conv.qual]):

// [ Note: If a program could assign a pointer of type T** to a pointer of type const T** (that is, if line #1
// below were allowed), a program could inadvertently modify a const object (as it is done on line #2). For
// example,
int main() {
  const char c = 'c';
  char* pc;
  const char** pcc = &pc; // #1: not allowed
  *pcc = &c;
  *pc = 'C'; // #2: modifies a const object
}
// — end note ]

【讨论】:

  • 内存位置最初不是恒定的,但尽管函数将其转换为const Node 指针,但我想知道为什么它会给出编译错误。我的意思是转换是从非常数到常量。
【解决方案2】:

p 是一个Node *,不能直接绑定到const Node* &amp;。需要先转换成const Node*,这是一个临时的,即右值,不能绑定lvaue-reference到non-const。

更改为Node* &amp; 解决了这个问题,p 可以直接绑定到Node* &amp; 而无需任何隐式转换。

顺便说一句,临时对象可以绑定到对const 的左值引用。将参数类型更改为const Node* const &amp; 工作正常。 LIVE

或者从传递引用更改为传递值(指针本身)为const Node*。 LIVE

【讨论】:

  • 那么,指针实际上不是作为常量指针传递的,而是指向常量内存位置的指针?
  • @VishalMahavar 是的,(从右到左阅读)const Node* &amp; 是对指向const Node 的(非常量)指针的引用。
  • 但是转换是从一个非常量内存位置到一个常量内存位置。那么,是禁止转换还是错误原因不同?
  • @VishalMahavar 不,Node* 可以隐式地转换为const Node*。问题是转换后的const Node* 是一个临时的右值,不能绑定到引用。如果参数类型是像const Node* 这样的非引用类型,那就没问题了。转换后的const Node* 将传递给display(作为参数复制)。
  • 所以它不同于传递普通参数,例如,int 可以传递给接受参数为const int &amp; 的函数。但这不适用于指针 ig。
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多