引用的c++ const语义
C++ const semantics for a reference
如果代码中有如下内容:
func(const base& obj)
const语义是什么意思?这里什么是常数?对象j是const reference to a non-const object
还是non-const reference to a const object
?
不存在"非const"引用,也就是说,一个引用总是绑定到同一个对象,并且无法改变这一点。"const type&"表示对const类型的引用。
obj
是对const
对象的引用。
不存在"非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基的引用,所以这意味着不允许更改被引用的对象。可以写成
func(const base& obj)
或
func(base const & obj)
使用左右规则读取这样的声明类型,对于这个简单的例子,只是从右边读取。更多信息在这里:
http://www.codeproject.com/KB/cpp/complex_declarations.aspxobj
是作为实参传递给func()
的对象(无论该对象是const还是非const)的常量引用
如果你写:func(B);
这意味着您不能在函数func()
B
的内容。(where 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
做错误的事情。