Why cannot a copy (copy) constructor be passed with a value?

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.