func(const base& obj)
const语义是什么意思?这里的常量是什么?obj是一个非const对象的const引用
还是一个const对象的非const引用
?
不存在所谓的“非const引用”,也就是说,引用总是绑定到同一个对象上,没有办法改变它。 “const type&”表示对const类型的引用。
obj
是指向常量对象的引用。
“非常量引用”是不存在的,因为一旦创建引用之后,它就不能被改变,也就不能指向其他东西。
func()
内,对该对象的使用仅限于那些在const
对象上有效的操作。因此,调用者知道调用func(obj)
不会改变obj
。 - Greg Hewgill如果没有const,您将无法将一个const对象发送到该函数。因此,始终添加const是一个积极的选择,尤其是当您为许多用户创建函数时。经典的例子是设置器函数。
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(B);
这意味着你不能在函数 func()
内更改 B
的内容
(其中 func(const base& obj)
)
例如:
// 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
错误的情况。
const base &obj
也可以被写成base const &obj
吗? - nitin_cherian