Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the parameter to a copy assignment operator should be a reference?

"opperator= should takes a parametor of the (of course,const best) ref of src obj",i see this in many books,but i try to use non-ref instead,it also works!so,whats the purpose of using ref?is it just to avoid copy from the param? my test code are,

#include <iostream>
#include <string>
using namespace std;

class Student{
public:
    Student& operator=(Student);
    string name;
    int num;
};

Student& Student::operator=(Student s)
{
    name=s.name;
    num=s.num;
    return *this;
}

int main(){
Student src;
src.name="haha";
src.num=11;
cout<<src.name<<" "<<src.num<<endl;
Student dst=src;
cout<<src.name<<" "<<src.num<<endl;
}
like image 360
aishuishou Avatar asked Mar 25 '26 06:03

aishuishou


2 Answers

There are really two issues here:

1) The copy-assignment operator you've defined doesn't get called. The line

Student dst=src;

doesn't call the copy-assignment operator! It calls the copy constructor, which is defined implicitly by the compiler. However, if you wrote

Student dst;
dst = src;

then operator= would be called.

2) Yes, the purpose is to avoid copying. When you call a function, including operator=, which takes a Student by value, the Student object argument has to be copied (through an implicit call to the copy constructor). If the function takes a reference, on the other hand, then no copy is made.

like image 153
Brian Bi Avatar answered Mar 27 '26 20:03

Brian Bi


Because otherwise it would be passed by value, which is a copy, so you would need to invoke the copy constructor to invoke the copy constructor ...

like image 37
user207421 Avatar answered Mar 27 '26 19:03

user207421