Don’ts and Dos
The following excerpt contains two examples of what not to do and one example of a good constructor:
String::String(){ str = "default string"; // oops, no new [] len = std::strlen(str);}String::String(const char * s){ len = std::strlen(s); str = new char; // oops, no [] std::strcpy(str, s); // oops, no room}String::String(const String & st){ len = st.len; str = new char[len + 1]; // good, allocate space std::strcpy(str, st.str); // good, copy value}
The first constructor fails to use new to initialize str. The destructor, when called for a default object, applies delete to str. The result of applying delete to a pointer not initialized by new is undefined, but it is probably ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access