简体   繁体   English

类成员引用变量是否具有内置的“ const-correctness”?

[英]Do class member reference variables have in-built “const-correctness”?

struct A {
  int &r; 
  A (int &i) : r(i) {}
  void foo () const {
    r = 5;  // <--- ok
  }
};

The compiler doesn't generate any error at r = 5; 编译器在r = 5;不产生任何错误r = 5; .
Does it mean that &r is already const-correct being a reference (logical equivalent of int* const ) ? 这是否意味着&r已经是const正确的引用(逻辑等效于int* const )? [Here is one related question.] [这里是一个相关的问题。]

I'm not sure exactly what you mean by "already const-correct", but: 我不确定“已经常量正确”是什么意思,但是:

Assigning to r is the same as assigning to whatever thing was passed into the constructor of A . 分配给r等同于分配给传递给A的构造函数的任何事物。 You're not modifying anything in the instance of A when you do this, so the fact that foo is declared const isn't an obstacle. 执行此操作时,您无需在A实例中进行任何修改,因此foo被声明为const的事实并不构成障碍。 It's very much as if you'd done this: 就像您已完成此操作一样:

struct A {
  int * r;
  A (int * i) : r(i) {}
  void foo () const { *r = 5; }
}

The fact that foo is const means that it doesn't modify anything in the A instance it's called on. foo是const的事实意味着它不会在被调用的A实例中修改任何内容。 There's no conflict between that and having it modify other data it was supplied with. 这与修改它提供的其他数据之间没有冲突。

Of course if you happened to arrange for r to be a reference to some member of A then calling foo would modify the instance of A after all. 当然,如果您碰巧将r引用为A某个成员,那么调用foo毕竟会修改A的实例。 The compiler can't catch all possible ways in which const ness of a member function might be violated; 编译器不能赶在一切可能的方式const成员函数的岬可能被侵犯; when you declare a member function const you're promising that it doesn't engage in any such subterfuge. 当声明成员函数const您保证它不会参与任何此类替代。

Yes, it's the logical equivalent of int* const . 是的,它在逻辑上等效于int* const

You may want to create and use appropriately qualified accessors in this case to prevent unwanted alterations to the value r references. 在这种情况下,您可能需要创建和使用适当限定的访问器,以防止对值r引用进行不必要的更改。

I interpret a const member function as implicitly inserting const just to the left of every data member that doesn't already have such a qualifier. 我将const成员函数解释为在每个尚未具有此类限定符的数据成员的左侧隐式插入const That const is already there implicitly for references ( int & const r; is illegal syntax). const已经隐式存在以供参考( int & const r;是非法语法)。 In other words, references are "already const-correct" to use your nomenclature. 换句话说,引用是“已经常量正确的”以使用您的命名法。

It would be nice if the const qualifier on a member function had the affect of inserting const in every possible valid position for every data member (eg, data member int ** foo; acts like int const * const * const foo; in a const member function), but that isn't what happens, and it isn't what the standard says will happen. 这将是很好,如果const的成员函数限定符有插入的影响const为每个数据成员每一个可能有效的位置(例如,数据成员int ** foo;行为像int const * const * const foo;const成员函数),但这不是要发生的事情,也不是标准所说的要发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM