设计引用由const引用传递的类的引用成员的行为的原因 [英] Design reasons for the behavior of reference members of classes passed by const reference

查看:110
本文介绍了设计引用由const引用传递的类的引用成员的行为的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有代码

#include <iostream>

struct A{
  int y;
  int& x;
  A():y(0),x(y){}
};



void f(int& x){
  x++;
}

void g(const A& a){
  f(a.x);
  //f(a.y);
}


int main(){
  A a;
  g(a);
  std::cout<<a.y<<std::endl;

}



$ b <$> on y是不允许的,因为a通过const修饰符
传递,然而,y的值可以在g()中通过调用f on x来修改;

inside g() calling f() on y is not allowed because a is passed with the const modifier however, the value of y can be modified inside g() by calling f on x;

struct B{
  int* x;  
}

g(const B&){
   *x++;
}

这是非常清楚的:我们有一个const指针非const int。
但是在前面的引用示例中,如果引用ARE的对象,为什么在这种情况下他们作为指针?

is allowed. This is perfectly clear: We have a const pointer to non-const int. But in the previous reference example, if references ARE the object, why do in this case they behave as pointers? What are the design policies under this behavior?

推荐答案

标准中的实际语言是


c ++ 11

1 - [...]
[注意:引用可以被认为是对象的名称。 -end note]

1 - [...] [ Note: A reference can be thought of as a name of an object. —end note ]

因此,如果引用是对象的名称,而不是对象本身,那么使得包围结构为 const 使得名称 const (这是无意义的,因为引用可以

So if a reference is a name of an object, not an object itself, then it makes sense that causing the enclosing structure to be const makes the name const (which is meaningless, as references can't be rebound), but not the object itself.

我们也看到


6 -
如果typedef,type template-parameter或decltype-specifier表示类型TR
,它是对类型T的引用,尝试创建类型lvalue reference

6 - If a typedef, a type template-parameter, or a decltype-specifier denotes a type TR that is a reference to a type T, an attempt to create the type "lvalue reference to cv TR" creates the type "lvalue reference to T" [...]

由于成员访问在 cv 对象上创建一个 cv 左值,同样适用, cv 资格已消失。

Since member access on a cv object creates a cv lvalue, the same applies and the cv qualification is extinguished.

这篇关于设计引用由const引用传递的类的引用成员的行为的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆