C++引用有两个属性:
指针是相反的:
为什么C++中没有"不可为空,可重复的引用或指针"?我想不出为什么参考不应该是可重复的一个很好的理由.
编辑: 问题经常出现,因为我通常使用引用,当我想确保"关联"(我在这里避免使用"引用"或"指针")永远无效.
我认为我从没想过"这个引用始终指的是同一个对象".如果引用是可重用的,那么仍然可以得到当前的行为:
int i = 3;
int& const j = i;Run Code Online (Sandbox Code Playgroud)
这已经是合法的C++,但毫无意义.
我重申我的问题: "'引用的背后是什么原因是对象'设计?为什么引用始终是同一个对象,而不是仅当声明为const时才被认为是有用的?"
干杯,菲利克斯
这是来自 C++20 规范 ( [basic.life]/8 )的代码示例:
struct C {
int i;
void f();
const C& operator=( const C& );
};
const C& C::operator=( const C& other) {
if ( this != &other ) {
this->~C(); // lifetime of *this ends
new (this) C(other); // new object of type C created
f(); // well-defined
}
return *this;
}
int main() {
C c1;
C c2;
c1 = c2; // well-defined
c1.f(); // well-defined; c1 refers to a new object of type …Run Code Online (Sandbox Code Playgroud)