CS/C/C++
[C/C++] Copy constructor, Copy assignment
amiz
2009. 9. 10. 11:07
참조 : The C++ Programming Language 3rd Ed.
여기서 객체가 대입이 되는데, 객체의 생성 시점에서 대입이 이루어 질 때는, copy constructor가 사용된다.
하지만, 이미 생성되어 있는 객체에 대입이 이루어 질 경우는 copy assignment가 사용된다.
따라서, copy assignment에서는 이미 생성되어 있는 객체를 cleanup 해주고 copy 해야 한다.
즉,
Sample X(10);
Sample Y(20);
Sample Z = X; // copy constructor
Z = Y; // copy assignment
세 가지 이상의 객체가 복사되는 경우가 있다.
1. 함수의 인자로 전달
2. 함수의 리턴 값
3. 예외 전달
결과는 다음과 같다.
Constructor : 0x22cc50
Copy constructor : 0x22cc30
Copy constructor : 0x22cc40
Copy assignment : 0x22cc50
Destructor : 0x22cc40
Destructor : 0x22cc30
Destructor : 0x22cc50
class X
{
// ...
X(Sometype); // constructor : create objects
X(const X&); // copy constructor
X& operator=(const X&) // copy assignment : cleanup and copy
~X() // destructor : cleanup
};
여기서 객체가 대입이 되는데, 객체의 생성 시점에서 대입이 이루어 질 때는, copy constructor가 사용된다.
하지만, 이미 생성되어 있는 객체에 대입이 이루어 질 경우는 copy assignment가 사용된다.
따라서, copy assignment에서는 이미 생성되어 있는 객체를 cleanup 해주고 copy 해야 한다.
즉,
Sample X(10);
Sample Y(20);
Sample Z = X; // copy constructor
Z = Y; // copy assignment
세 가지 이상의 객체가 복사되는 경우가 있다.
1. 함수의 인자로 전달
2. 함수의 리턴 값
3. 예외 전달
#include <iostream>
using namespace std;
class Sample
{
public:
Sample(int e);
Sample(const Sample&);
Sample& operator=(const Sample&);
~Sample();
private:
int _elem;
};
Sample::Sample(int e) : _elem(e)
{
cout << "Constructor : " << this << endl;
}
Sample::Sample(const Sample& s)
{
cout << "Copy constructor : " << this << endl;
_elem = s._elem;
}
Sample& Sample::operator=(const Sample& s)
{
cout << "Copy assignment : " << this << endl;
_elem = s._elem;
return *this;
}
Sample::~Sample()
{
cout << "Destructor : " << this << endl;
}
Sample g(Sample s)
{
return s;
}
int main(void)
{
Sample s(1);
s = g(s);
return 0;
}
결과는 다음과 같다.
Constructor : 0x22cc50
Copy constructor : 0x22cc30
Copy constructor : 0x22cc40
Copy assignment : 0x22cc50
Destructor : 0x22cc40
Destructor : 0x22cc30
Destructor : 0x22cc50