複製構造函數用於很多事情,例如當我需要使用指針或爲對象動態分配內存時。但看這個例子在tutorialpoint.com
:解釋複製構造函數示例
#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;
}
結果是:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
,當我註釋掉(拷貝構造函數)和內析構函數的代碼中,我得到了相同的結果:
Normal constructor allocating ptr
Length of line : 10
那麼在這裏使用複製構造函數還是不同?另外爲什麼「釋放記憶!」發生兩次?
看看結果。在第一個例子中,你將分配兩個不同的整數並釋放它們。第二,你分配一個並釋放它兩次。不好。 – chris
它沒有在第二個例子中釋放,我只是忘記評論「cout <<」釋放內存!「在構造函數中的語句,所以它實際上並沒有釋放 – Omar
然後你已經分配了一些你還沒有釋放的東西,如果它開始變得比創建一個和結束程序更復雜,就是內存泄漏 – chris