[英]Why does assignment operator call both copy ctor and assignment operator?
[英]Why does assignment to a reference use the copy assignment operator?
對於以下示例:
#include <iostream>
using namespace std;
class Obj {
public:
Obj& operator=(const Obj& o) {
cout << "Copy assignment operator called" << endl;
return *this;
}
};
Obj o;
int update(Obj& o) {
o = ::o;
}
int main() {
Obj o2;
update(o2);
}
我得到結果:
Copy assignment operator called
為什么在將對象分配給引用時使用復制分配? 為什么不只是更新引用以指向分配的對象? 這是慣例問題還是背后有原因?
分配給引用是分配給引用所指的對象,而不是引用本身。 因此,您的update
功能相當於:
o2 = ::o;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.