C ++ Learning -- copy constructor

Source: Internet
Author: User

The copy constructor is a very subtle function. If you cannot fully understand it, many inexplicable errors may occur.ProgramTo describe the secrets in detail.

1 hermit member function in C ++

(1) default constructor, if not defined

(2) copy the constructor, if not defined

(3) value assignment operator, if not defined

(4) default destructor, if not defined

(5) Address operator, if not defined

2. Focus on copying Constructor

The copy constructor refers to copying an object to a new object, that is, it is used in the initialization process, rather than in the general value assignment process.

Classname (const classname &);

(1) Copying constructor Functions

Copy non-static members one by one, and copy values. This will cause a problem. When there is a pointer in the object, it is only the address of the copied pointer, instead of the actual content. In this case, we must display the definition of the copy constructor to solve this problem.

(2) The copy constructor does not add the number of new objects to the constructor, but it will call the destructor, which will result in inaccurate counts in the constructor.

(3) As mentioned in (1), it just copies the pointer address. Therefore, when an object calls the destructor, the object that calls the Destructor first releases the space pointed to by the pointer. However, when other objects call the Destructor again, the space will be released, this causes the same space to be deleted twice, which is often garbled.

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.