복사 생성자는 포인터를 사용해야하거나 객체에 동적으로 메모리를 할당해야하는 경우와 같이 많은 경우에 사용됩니다.복사 생성자 예제 설명
이#include <iostream>
using namespace std;
class Line
{
public:
int getLength(void);
Line(int len); // simple constructor
Line(const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength(void)
{
return *ptr;
}
void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main()
{
Line line(10);
display(line);
return 0;
}
결과는 다음과 같습니다 : 그러나 tutorialpoint.com
에서이 예를보고
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
내가 (복사 생성자)와 소멸자 내부의 코드를 주석 때이 같은 결과를 얻었다 :
을Normal constructor allocating ptr
Length of line : 10
여기에 복사 생성자를 사용하는 것과 다른 점은 무엇입니까? 또한 왜 "Freeing Memory!" 두 번 나타 납니까?
결과를 살펴보십시오. 첫 번째 예제에서는 두 개의 서로 다른 int를 할당하고 둘 다 해제합니다. 두 번째 단계에서는 하나를 할당하고 두 번 해방하십시오. 안좋다. – chris
두 번째 예제에서 해제되지 않은, 나는 방금 "cout <<"메모리를 해제 주석을 깜빡!"문을 생성자 내부에서 처리하므로 실제로 해제되지 않았습니다. – Omar
그런 다음 해제하지 않은 내용을 할당 했으므로 프로그램을 끝내고 프로그램을 종료하는 것보다 복잡해지기 시작하면 메모리 누수가 발생합니다. – chris