Have you ever paid attention to memory management when using classes? I have an elementary quiz about the basic concept of memory management in standard C++. This quiz is from my teaching experience because I found many programmers usually make the same mistake.
Now, take a look at the quiz. Please don’t worry if you cannot give a answer. Paying attention to such code from now on is the most important thing you need to learn.
Quiz
How does the following code work?
What will happen during the running process? Why?
If there is a problem, how will you solve it?
class A { private: char* pchTest; public: explicit A(char* const pchInitialText); virtual ~A(); char* GetContent(void)const{return pchTest;} }; A::A(char* const pchInitialText) { pchTest = new char[strlen(pchInitialText)+1]; strcpy(pchTest,pchInitialText); } A::~A() { delete [] pchTest; pchTest = NULL; } void show(A clsAtest) { printf("%s",clsAtest.GetContent()); } int main(void) { A Atest("Just Test!"); show(Atest); return 0; }
Hints
How is the parameter transferred into the functions as shown below?
void FunctionName(ValueType para); void FunctionName(ValueType *para); void FunctionName(ValueType ¶);
Have any idea? I will share my thoughts on the next page.