programing tip

할당 연산자와 복사 생성자의 차이점은 무엇입니까?

itbloger 2020. 8. 30. 07:49
반응형

할당 연산자와 복사 생성자의 차이점은 무엇입니까?


C ++에서 할당 생성자와 복사 생성자의 차이점을 이해하지 못합니다. 다음과 같습니다.

class A {
public:
    A() {
        cout << "A::A()" << endl;
    }
};

// The copy constructor
A a = b;

// The assignment constructor
A c;
c = a;

// Is it right?

할당 생성자 및 복사 생성자의 메모리를 할당하는 방법을 알고 싶습니다.


복사 생성자는 초기화하는 데 사용됩니다 이전에 초기화되지 않은 다른 개체의 데이터에서 개체를.

A(const A& rhs) : data_(rhs.data_) {}

예를 들면 :

A aa;
A a = aa;  //copy constructor

할당 연산자는 a의 데이터를 교환하는 데 사용됩니다 이전에 초기화 다른 개체의 데이터와 객체를.

A& operator=(const A& rhs) {data_ = rhs.data_; return *this;}

예를 들면 :

A aa;
A a;
a = aa;  // assignment operator

복사 구성을 기본 구성과 할당으로 바꿀 수 있지만 효율성이 떨어집니다.

(부수적으로 : 위의 구현은 컴파일러가 무료로 제공하는 것과 정확히 일치하므로 수동으로 구현하는 것은별로 의미가 없습니다.이 두 가지 중 하나가 있으면 일부 리소스를 수동으로 관리 할 가능성이 큽니다. 이 경우 The Rule of Three 에 따라 다른 하나와 소멸자가 필요할 가능성이 큽니다.)


복사 생성자와 할당 연산자의 차이는 초보 프로그래머에게 많은 혼란을 야기하지만 실제로 그렇게 어렵지는 않습니다. 요약 :

  • 복사하기 전에 새 객체를 만들어야하는 경우 복사 생성자가 사용됩니다.
  • 복사하기 전에 새 개체를 만들 필요가없는 경우 할당 연산자가 사용됩니다.

할당 연산자의 예 :

Base obj1(5); //calls Base class constructor
Base obj2; //calls Base class default constructor
obj2 = obj1; //calls assignment operator

복사 생성자의 예 :

Base obj1(5);
Base obj2 = obj1; //calls copy constructor

The first is copy initialization, the second is just assignment. There's no such thing as assignment constructor.

A aa=bb;

uses the compiler-generated copy constructor.

A cc;
cc=aa;

uses the default constructor to construct cc, and then the *assignment operator** (operator =) on an already existing object.

I want know how to allocate memory of the assignment constructor and copy constructor?

IDK what you mean by allocate memory in this case, but if you want to see what happens, you can:

class A
{
public :
    A(){ cout<<"default constructor"<<endl;};
    A(const A& other){ cout<<"copy constructor"<<endl;};
    A& operator = (const A& other){cout <<"assignment operator"<<endl;}
};

I also recommend you take a look at:

Why is copy constructor called instead of conversion constructor?

What is The Rule of Three?


What @Luchian Grigore Said is implemented like this

class A
{
public :
    int a;
    A(){ cout<<"default constructor"<<endl;};
    A(const A& other){ cout<<"copy constructor"<<endl;};
    A& operator = (const A& other){cout <<"assignment operator"<<endl;}
};

void main()
{
    A sampleObj; //Calls default constructor
    sampleObj.a = 10;

    A copyConsObj  = sampleObj; //Initializing calls copy constructor

    A assignOpObj; //Calls default constrcutor
    assignOpObj = sampleObj; //Object Created before so it calls assignment operator
}

OUTPUT


default constructor


copy constructor


default constructor


assignment operator



the difference between a copy constructor and an assignment constructor is:

  1. In case of a copy constructor it creates a new object.(<classname> <o1>=<o2>)
  2. In case of an assignment constructor it will not create any object means it apply on already created objects(<o1>=<o2>).

And the basic functionalities in both are same, they will copy the data from o2 to o1 member-by-member.


In a simple words,

Copy constructor is called when a new object is created from an existing object, as a copy of the existing object. And assignment operator is called when an already initialized object is assigned a new value from another existing object.

Example-

t2 = t1;  // calls assignment operator, same as "t2.operator=(t1);"
Test t3 = t1;  // calls copy constructor, same as "Test t3(t1);"

I want to add one more point on this topic. "The operator function of assignment operator should be written only as a member function of the class." We can't make it as friend function unlike other binary or unary operator.


Something to add about copy constructor:

  • When passing an object by value, it will use copy constructor

  • When an object is returned from a function by value, it will use copy constructor

  • When initializing an object using the values of another object(as the example you give).

참고URL : https://stackoverflow.com/questions/11706040/whats-the-difference-between-assignment-operator-and-copy-constructor

반응형