In the C ++ class, it is sometimes used to call the passed value (Object object as a parameter). In this case, be careful! Especially when the object you pass a value has a long lifecycle rather than a temporary object (lifecycle segment. Let's take a look at the following situation:
#include <iostream>using namespace std; class Text{private: char * str; public: Text(){str = new char[20];::memset(str,0,20);} void SetText(char * str) { strcpy(this->str,str); } char * GetText() const{return str;} ~Text() { cout << "~Text Destruction" << endl; delete [] str; cout << "~Text Over" << endl; }}; void Print(Text str){ cout << str.GetText() << endl;} int main(){ Text t; t.SetText("abc"); Print(t); return 1;} |
The execution result program crashes. Cause:
Print (Text Str) does not perform deep copy when copying and constructing STR; when print exits, it is a temporary object (constructed at the initial time of the function ), analyze STR, and there is no flaw at this time; but return to main, and then exit main, and then analyze t, however, the content in STR in T has been destroyed. A memory error occurs because a memory space is destroyed twice.
Solution:
- Override the shortest copy. Make appropriate adjustments in different situations like the following versions:
#include <iostream>using namespace std; class Text{private: char * str; public: Text(){str = new char[20];::memset(str,0,20);} Text(Text &t) { str = new char[20]; strcpy(str,t.GetText()); } void SetText(char * str) { strcpy(this->str,str); } char * GetText() const{return str;} ~Text() { cout << "~Text Destruction" << endl; delete [] str; cout << "~Text Over" << endl; }}; void Print(Text str){ cout << str.GetText() << endl;} int main(){ Text t; t.SetText("abc"); Print(t); return 1;} |
- (Recommended) do not use value transfer for calling. As shown in the following print version:
void Print(Text &str){ cout << str.GetText() << endl;} |
- Unless all the members in the object readNon-pointer memory contentSo proceed with caution.