Deep copy and shallow copy problems in C + +

Source: Internet
Author: User

In C + + deep copy and shallow copy problem is more important, a brief introduction to the meaning of deep copy and shallow copy, in C + + class by default There are six functions, copy constructor is included in the process of running the program, if there is no custom copy constructor, Then the program will use its own default constructor, which, in this process, is called a shallow copy, and the user-defined copy constructor is called a deep copy.

The main differences between deep and shallow copies are illustrated in the following practical examples:

#include <iostream>

#include <string>

using namespace Std;

Class A

{

Private

Char* _a;

Public

A (char* a=/* "" */null)

{

_a = new Char[strlen (a) + 1];

cout << "A ()" << Endl;

}

~a ()

{

if (_a! = NULL)

Delete _a;

_a = NULL;

cout << "~a ()" << Endl;

}

void Show ()

{

cout << _a << Endl;

}

};

int main ()

{

A ("123");

A AA (a);

GetChar ();

return 0;

}

This time the object a inside _a and the object AA in the _a share a space, this time when the program calls the destructor, the shared space will be released two times, the program will be problematic.

Deep copy, the user customizes a copy constructor itself, as shown in the following procedure

#include <iostream>

#include <string>

using namespace Std;

Class A

{

Private

Char* _a;

Public

A (char* a=/* "" */null)

{

_a = new Char[strlen (a) + 1];

cout << "A ()" << Endl;

}

~a ()

{

if (_a! = NULL)

Delete _a;

_a = NULL;

cout << "~a ()" << Endl;

}

A (const a &a)

{

_a = new Char[strlen (a._a) + 1];

strcpy (_a, a._a);

}

void Show ()

{

cout << _a << Endl;

}

};

int main ()

{

A ("123");

A AA (a);

cout << &a << Endl;

cout << &aa << Endl;

GetChar ();

return 0;

}


This article is from the "local and static Variables" blog, reproduced please contact the author!

Deep copy and shallow copy problems in C + +

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.