Questions related to deep copy of the C++ constructor.

Asked 2 years ago, Updated 2 years ago, 26 views

I have a question because I don't understand the code of the second generator of public in the code below. The role of the code is http://blog.According to data from eairship.kr/168.. After memory space is allocated, the string is copied and then the address of the allocated memory is stored in str. However, I don't understand how the code below plays that role.

        MyClass(const MyClass& mc){
            str = new char[strlen(mc.str)+1];
            strcpy(str, mc.str);

In the code above, I don't understand the part called const MyClass&mc in the factor first. I just know that Const is an address operator, which is a constant that prevents it from touching the factor.

For your information, below is the full code with the above code.

//Deep Copy
#include <iostream>
using namespace std;

class MyClass
{
    private:
        char *str;
    public:
        MyClass(const char *aStr){
            str = new char[strlen(aStr)+1];
            strcpy(str, aStr);
        }
        MyClass(const MyClass& mc){
            str = new char[strlen(mc.str)+1];
            strcpy(str, mc.str);*
        }
        ~MyClass(){
            delete []str;
            cout << "~MyClass() called!" << endl;
        }
    void ShowData(){
        cout << "str: " << str << endl;
        }
};

int main(){
    MyClass mc1("MyClass!");
    MyClass mc2 = mc1;

    mc1.ShowData();
    mc2.ShowData();
    return 0;
}

c++

2022-09-22 20:40

2 Answers

Deep copying is nothing more than simply copying an object, and when the object is copied, it becomes a pointer address, and when the object to be copied disappears, it disappears to the pointer address on the object, so the pointer address of the copied object will no longer be written. So in order to copy the value,

 str = new char[strlen(mc.str)+1];
 strcpy(str, mc.str);

It's doing that. 1.Const is used to protect objects passed by parameters. & is... I don't remember exactly LOL;;; I don't really touch C++ Remember only as much as an operator to refer to an object. Anyway, the object that was delivered I'll refer to it. It's more efficient to do reference operations than just copy values or objects.

The length of the string can be determined through the 2, 3 strlen function, but +1 is for the null value. If you use string, this is not necessary, but to write a char array, you need to have a null at the end of the string. So we went through this process to copy it to a new object as long as the string. You can just do a new char[100] and then put a null at the end of the string, but that'll waste space, right?

I don't know if the answer went well.


2022-09-22 20:40

There is a slight difference in c++, which is the & lvalue parameter. Search '&,&&reference declaration' for a description of this


2022-09-22 20:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.