[英]C++ const semantics for a reference
如果代码中有类似的内容:
func(const base& obj)
const语义是什么意思? 这里有什么不变的? obj是const reference to a non-const object
non-const reference to a const object
还是const reference to a non-const object
的non-const reference to a const object
?
obj
是对const
对象的引用 。
没有“非const引用”这样的东西,因为在创建引用后不能更改引用其他内容。
没有“非const”引用这样的东西,也就是说,引用总是绑定到同一个对象,并且没有办法改变它。 “const type&”表示对const类型的引用。
它被称为const引用。 您对已传递的数据进行“参照访问”,但无法对其进行修改。
如果没有const,您将无法将const对象发送到该函数。 因此添加const总是有利的。 特别是在为许多用户创建功能时。 经典示例是setter函数。
x->setXsth(sth& obj) // works only with non-const object.
x->setXsth(const sth& obj) //works with const object and non-const.
obj是对const base的引用,因此它意味着不允许更改引用的对象。 它可以写成
func(const base& obj)
要么
func(base const & obj)
使用左右规则来读取这样的声明类型,对于这个简单的例子,只需从右边读取它即可。 更多内容如下:
obj
是对参数传递给func()
的对象的常量引用(对象是const或非const func()
如果你写: func(B);
这意味着您无法在函数func()
更改B
的内容
(其中func(const base& obj)
)
一些未经请求的答案/观点: const修饰符修改其左侧的任何内容,除了您正在使用的一个结构(在这种情况下,它会修改右边的任何内容)。 我发现在我想要修改的任何内容中,总是立即粘贴const更容易,并从右到左阅读语句。 也许这不是最好的做事方式,但它有助于我保持原状。
例子:
// these two statements are equivalent
const int x = 5; // special case usage
int const x = 5;
// using the LHS syntax makes multiple consts easier to understand
int const y = 6;
int const * const x = &y; // x is a const pointer to const int
// const can apply to pointers but not to references
int const & const z = y; // redundant, references are always const
正如其他答案所说, obj
是对const base
对象的引用。 但是,这并不意味着它引用的对象要么具有完全base
类型,要么它引用的对象是const
,只是func
不能通过该引用修改obj
。 例如:
struct derived : base { ... };
derived d;
func(d);
是合法的,并且:
bool other_func(const base& b, other_object& o) {
base b_copy = b;
o.foo();
return b_copy == b;
}
如果o
具有对b
(或其中的某些内容)的内部非const引用,并且o.foo()
修改b
则可能返回false
。 这对像这样的功能具有实际意义
std::string::operator=(const std::string& other);
对于my_str = my_str
,一个天真的实现可能会做错的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.