简体   繁体   中英

Return type of operator = in C++

I just have a clarification to make. Say for example I want to override the operator =. From what I've read, this should return a REFERENCE to the object. And as what I've read from another source, a Reference is just an alternate name to the object. So could I do this?

MyObject MyObject::operator =(const MyObject &o2) {
    //insert processing code here
    return *this;
}

rather than this?

MyObject& MyObject::operator =(const MyObject &o2) {
    //insert processing code here
    return *this;
}

In the first case, you return a copy of *this , not a reference to *this . So you should stick to the second case. There is a big difference between those 2 cases, especially for types that are "expensive" to copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM