標籤:c++ 拷貝建構函式
The copy constructor is a special kind of constructor which creates a new object which is a copy of an existing one, and does it efficiently.
(拷貝建構函式是一種特別的建構函式,用於複製已經存在的對象到新產生的對象,這是一種高效的方式。)
Here below is a simple declaration of a copy constructor:
(下面是拷貝建構函式簡單的聲明:)
class string{ string(); ~string(); string(const string &s) { copy(s.m_str); }};
Now you can use it as follow:
(現在,你可以按照下面的方式使用拷貝建構函式)
// create an object which is copy of another objectstring s1("hello");string s2(s1); // copy constructor activated// create an object as a copy of a temporary objectstring s3(string("abc"));string s4 = s1;// object s4 does not activate the constructor, but its copy constructor to make only a copy of s1, rather than building a new object
you have to use const in the argument at the copy constructor to create an object as a copy of a temporary object: e.g. string(const string &s).
(在拷貝建構函式中,你必須使用const關鍵字作為參數)
to make things clear, you can create a new object as copy of a different object without using a copy constructor, like this:
(進一步將,你可以不使用拷貝建構函式來複製一個對象到另一個新對象)
string s4;s4.set(s1);
this is an example of inefficient code. Since s4 first call its constructor to build a new object and then it make a bit-wise copy of s1. The whole process of calling the constructor to build an object which next is being rewritten, is wasteful, takes time and resources. Copy constructor allow you to prevents this inefficiency.
(這是一個效率低下的代碼。由於s4首先需要調用自己的建構函式建立一個對象,然後把s1按位拷貝到s4.整個處理的過程是調用建構函式建立一個對象,然後重寫這個對象,這是一種浪費時間、浪費資源的做法。拷貝建構函式可以幫你預防這種低效。)
Default copy constructor
If the programmer did not declared the copy constructor for a class, the compiler will add its own default copy constructor for the objects derived from that class.
Default copy constructor does a very simple operation, they will do a bit-wise (member-wise) copy of an object, which means that the object will be copied bit by bit.
(如果程式員沒有提供拷貝建構函式,那麼編譯器會自動產生預設的拷貝建構函式。預設的拷貝建構函式會執行簡單的操作,即按位拷貝對象。)
string s1("hello");string s2(s1);string s2 = s1; //the same as above
There is a danger in copying an object bit by bit, if the object contains pointers since the pointer address will be copied in the process resulting in two different objects that share the same memory buffer. You can imagine what will happen when two copies of an object calls their destructors one after the other. The first object that call its destructor will have no problems, since it will try to deallocate the pointer and succeed, but the second objects destructor try to deallocate a pointer which does not exist anymore and the whole application crashes!
(如果對象中含有指標,那麼按位拷貝就是很危險的。是因為兩個對象的指標會指向同一片記憶體。你可以想象一下,當兩個拷貝的對象去調用他們的解構函式的時候會發生什麼。首先調用解構函式的對象不會有任何問題,但是第二個對象的解構函式就會嘗試去釋放不存在的資源,這樣會道是整個應用程式的崩潰。)
For a situation where an object contain pointers we have to write our own copy constructor that will prevent situations like those mentioned above.
(對於類對象包含指標的情況下,我們要編寫自己的拷貝建構函式,這樣可以防止上述情況的發生)
There are 3 situations in which the copy constructor is called:
When we make copy of an object.
When we pass an object as an argument by value to a method.
When we return an object from a method by value.
(有三種情況下拷貝建構函式會被調用:
當拷貝對象時候
當按值傳遞一個對象作為方法參數的時候
當按值返回一個對象時候)
we saw the first scenario above, and we will now look at the other two scenarios.
(我們已經在上述中展示了第一種情況,下面我將會帶領大家看看後兩種情況。)
When objects are passed to a function as arguments by value, a bit wise copy of the object will be passed to the function and placed on the stack, therefor the constructor of the object will not be called. It make sense if you think of it, you want to pass an object in a certain state containing the data you need for the function to process, if you wanted it in the initialization state with its default data, you could just create it inside the function instead of passing it as an argument.
(當一個對象按值傳遞給一個函數作為參數,對象將會按位拷貝到函數中,並且置於棧中。所以此時對象的建構函式不會被 調用。當你希望傳遞的對象有初始化值的時候,你應該在函數的內部建立它來代替作為參數傳給函數。)
When the function end, the constructor of the object will be called. This is also make sense since the object was passed by value and its data will not be needed outside the function scope.
(當函數結束的時候,對象的解構函式就會被調用。這似乎也很合理,因為我們是按值進行的傳遞,在超出函數的作用範圍後,我們不需要該變數。)
No pay attention to this, the situation in which only the object destructor is called can make great deal of troubles. Think what will happen when the object holds a pointer to some address in the memory. When this object is passed as argument to a function the pointer in the new temporary created object will hold the same address as the original object, since its a bit wise copy. When the function ends, the destructor will free the address pointed by the pointer. From this point, if the destructor of the original object will be called it will try to free an address which already free, and we all know what it the consequences of that …
(沒有注意到的是,對象的解構函式調用後會引起很大的麻煩。想想如果對象中包含了指向地址的指標會發生什麼。由於是按位拷貝,當傳遞一個對象給函數作為參數的時候,新產生的臨時性的對象的指標將會與 原來對象的指標指向同一個地址。當函數結束的時候,解構函式將會釋放指標指向的地址。從這點來看,如果原來對象 的解構函式被調用,它將會釋放已經釋放的記憶體,我們都知道會發生什麼樣的後果。)
lets look at an example to make things clear.
Here we define string class which holds a char* pointer:
(讓我們看看下面的例子,以便更加清楚 這裡我們定義的string類包含了一個char*指標)
class string{ // constructor string(char* aStr) { str = new char[sizeof(aStr)]; strcpy (str,aStr); } // destructor ~string() { del str; } char *getChars(){ return str; } char* str;};
now we will write a function that receive a string object as an argument.
(現在,我們寫一個接受string對象作為參數的函數:)
void function (string str){// do somthing}
Lets look what will happen when we call this function :
(當我們調用這個函數的時候看看會發生什麼:)
void main (){ string str("hello"); function(str); function(str); // program crush}
The first time we call function(str) everything works properly, when the function ends, the input argument on the stack is destroyed, and its destructor will be called, and delete the pointer.
The second time we call the function , everything still works properly, but when the function ends, the constructor will try now to free the address pointed by str, and crash.
(第一次調用function函數的時候一切都很正常,當函數結束的時候,棧上的參數會被銷毀,所以對象的解構函式會被調用,並且刪除指標指向的內容。 第二次調用function函數的時候,一切似乎同樣正常。但當函數結束的時候,解構函式會試圖去釋放指標str指向地址的內容,這樣就會造成奔潰。)
The copy constructor come to help us solve this kind of problems. Here is a solution:
(拷貝建構函式會協助我們解決這樣的問題,下面是解決方案:)
class string{ // constructor string(char* aStr) { str = new char[sizeof(aStr)]; strcpy (str,aStr); } string(string &strObj) { tmpStr = strObj.getChars(); str = new tmpStr[sizeof(tmpStr)]; strcpy (str,tmpStr); } // destructor ~string() { del str; } char* str;};
The same way we can handle the third scenario where a method returns an object:
(同樣的方式,我們示範了上訴的第三種情況,即返回一個對象)
class string{ public: string(char* aStr) { str = new char[ strlen(aStr) + 1 ]; strcpy (str,aStr); } string(string &strObj) { str = new char[ strObj.str ]; strcpy( str, strObj.str ); } string &string::operator=(const string &s) { string temp( s ); std::swap( temp.str, str ); return *this; } // destructor ~string() { delete[] str; } private: char* str;};
C++ Copy Constructor in depth (深入理解C++拷貝建構函式)