English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Problems encountered when initializing pointer members of an object with new
When initializing pointer members using new in the constructor, the destructor must use delete, and new corresponds to delete, while new[] corresponds to delete[].
In the case of multiple constructors, it is necessary to use new in the same way, or not use new, or not use new[], because there is only one destructor, and all constructors must be compatible with the destructor.
PS. Of course, when initializing pointers with new in the constructor, you can initialize the pointer to be empty (0/NULL or C++11nullptr) because delete is compatible with null pointer whether it is with or without [].
You need to define a copy constructor and an assignment constructor yourself, and initialize one object to another object in the form of deep copy, as follows:
Copy constructor:
String:String(const String & st) { num_Strings++; len = st.len; str = new char[len+1]; std::strcpy(str, st.str()); }
Assignment constructor:
String & String:operator=(const String & st) { if(this == &st) return *this; else delete[] str; len = st.len; str = new char[len+1]; std::strcpy(str, st.str()); return *this; }
That's all for the content of this article. I hope the content of this article can bring a certain amount of help to everyone's learning or work, and I also hope to support the Yelling Tutorial more!
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not edit the content manually, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)