Consider the following code :
class Apple {
public:
void getACrunch() {}
};
Apple eatSome(Apple a) {
a.getACrunch();
return a;
}
int main() {
Apple a;
a = eatSome(a);
}
On the last line of the main function, how many times a copy of the Apple object is performed, using either its copy constructor or copy assignment operator ?
There are three copies here :
eatSome function uses a call by value, so before starting the function scope the local variable a is created using something like this :Apple a = a; // the second a is the a defined in outside of the function scope, in the `main` function
// => copy constructor
eatSome also use a return by value, which means that at the end of the function execution, a "temporary" variable is allocated using something that looks like thatApple _result_ = a // a is the local variable from the function scope
// => copy constructor
a = _result_ // _result_ is where eatSome(a) is temporary stored
// => copy assignment operator
Since no move constructor or move assignment operator is implemented, the compiler defines and use per default some copy of the data, so the three copies here.
To check this, you can use the program below :
#include <iostream>
using std::cout, std::endl;
class Apple {
public:
void getACrunch() {}
Apple() = default;
Apple(const Apple& other) {
cout << "Copy constructor" << endl;
}
Apple& operator=(const Apple& other) {
cout << "Copy assignment operator" << endl;
return *this;
}
};
Apple eatSome(Apple a) {
cout << " -- starting eatSome" << endl;
a.getACrunch();
return a;
}
int main() {
Apple a;
cout << " -- before eatSome" << endl;
a = eatSome(a);
cout << " -- after eatSome" << endl;
}
for which the output is
-- before eatSome
Copy constructor
-- starting eatSome
Copy constructor
Copy assignment operator
-- after eatSome