When you try to write the copy constructor as a value for passing, you will find that the compilation fails. The error message is as follows:
Error: invalid constructor; you probably meant's (const S &) '(meaning: invalid constructor. you should write it ...)
When a compilation error occurs, you start to struggle. Why do I need to use reference to transfer the copy constructor? I found a lot of information online, it basically means that if values are passed, an endless loop may occur. For this reason, the compiler may not allow the copy constructor to pass values, or the C ++ standard stipulates this.
If this is the cause of an endless loop, it should be like this:
# Include <iostream>
Using namespace std;
Class S
{
Int;
Public:
S (int x): a (x ){}
S (const S st) {this-> a = st. a;} // copy the constructor
};
Int main ()
{
S s1 (2 );
S s2 (s1 );
Return 0;
}
When s2 is initialized, the copy constructor of s2 is called. Because it is a value transfer, the system will re-apply for a space for the form parameter st, then, call its own copy constructor to pass the value of the s1 data member to st. When calling its own copy constructor, it is also because the value is passed, so...
That is to say, if you call the copy constructor, you will apply for a new space. If you re-apply for a new space, you will call the copy constructor. This leads to an endless loop.
Therefore, the copy constructor cannot be a value transfer.
Author c Xiaojia