在构造函数中使用new的注意事项

最近在复习C++的类方面的知识,看的是《C++ Primer Plus》,觉得此小结甚好,所以copy过来了。


Things to Remember When Using new in Constructors

By now you’ve noticed that you must take special care when using new to initialize pointer members of an object.In particular,you should do the following:
1) If you use  new to initialize a pointer member in a constructor,you should use delete in the destructor.
2) The uses of  new and delete should be compatible.You should pair  new with delete and new [] with delete [] .
3) If there are multiple constructors,all should use  new the same way—either all with brackets or all without brackets.There's onlyone destructor,so all constructors have to be compatible with that destructor.However,it is permissible to initialize a pointerwith  new in one constructor and with the null pointer ( 0 ,or,with C++11, nullptr ) in another constructor because it’s okay toapply the  delete operation (with or without brackets) to the null pointer.


NULL or 0 or nullptr?

Historically, the null pointer can be represented by  0 or by  NULL , a symbolic constant defined as 0 in several header files. C programmers often use  NULL instead of  0 as a visual reminder that the value is a pointer value, just as they use  '\0' instead of  0 for the null character as a visual reminder that this value is a character. The C++ tradition, however, has favored a simple  0 instead of the equivalent  NULL . And, as mentioned earlier, C++11 offers the nullptr keyword as a better alternative.


I) You should define a copy constructor that initializes one object to another by doing deep copying.Typically,the constructor should emulate the following example:

String::String(const String & st)
{
num_strings++; // handle static member update if necessary
len = st.len; // same length as copied string
str = new char [len + 1]; // allot space
std::strcpy(str, st.str); // copy string to new location
}
In particular,the copy constructor should allocate space to hold the copied data,and it should copy the data,not just the address of the data.Also it should update any static class members whose value would be affected by the process.


II) You should define an assignment operator that copies one object to another by doing deep copying.Typically,the class method should emulate the following example:

String & String::operator=(const String & st)
{
if (this == &st) // object assigned to itself
return *this; // all done
delete [] str; // free old string
len = st.len;
str = new char [len + 1]; // get space for new string
std::strcpy(str, st.str); // copy the string
return *this; // return reference to invoking object
}
In particular,the method should check for self-assignment;it should free memory formerly pointed to by the member pointer;it should copy the data,not just the address of  the data;and it should return a reference to the invoking object.


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 bad.Any of the following would be okay:
String::String()
{
len = 0;
str = new char[1]; // uses new with []
str[0] = '\0';
}

String::String()
{
len = 0;
str = 0; // or, with C++11, str = nullptr;
}

String::String()
{
static const char * s = "C++"; // initialized just once
len = std::strlen(s);
str = new char[len + 1]; // uses new with []
std::strcpy(str, s);
}
Next,the second constructor in the original excerpt applies  new ,but it fails to request the correct amount of memory;hence, new returns a block containing space for just one character.Attempting to copy a longer string to that location is asking for memory problems.Also the use of  new without brackets is inconsistent with the correct form of the other constructors. The third constructor is fine.


Finally,here’s a destructor that doesn’t work correctly with the previous constructors:
String::~String()
{
delete str; // oops, should be delete [] str;
}
The destructor uses  delete incorrectly.Because the constructors request arrays of characters,the destructor should delete an array.

你可能感兴趣的:(C++,new,构造函数,分配内存)