Considerations when using new in the C++ constructor

  • 2020-05-17 05:56:49
  • OfStack

Problems encountered when initializing pointer members in an object using new

If new is used in the constructor to initialize pointer members, then delete must be used in the destructor, and new corresponds to delete, and new[] corresponds to delete[].

In the case of multiple constructors, new must be used in the same way, new must not be used, new[] must not be used, because there is only one destructor, and all constructors must be compatible with fictional functions.

PS. Of course, when initializing a pointer using new in a constructor, you can initialize the pointer to null (0/NULL or nullptr in C++11), because delete is compatible with null Pointers with or without [].

You need to define a copy constructor and an assignment constructor by yourself, and initialize one object to another object and copy one object to another object in a deep copy way, as follows:

Copy constructor:

Allocate enough space to store replicated data Copy data, not just addresses Update the affected static class members

String:String(const String & st)
{
  num_Strings++;
  len = st.len;
  str = new char[len+1];
  std::strcpy(str,st.str);
}

Assignment constructor:

Check for self-replication Points to memory before freeing the member pointer Copying data is more than just addresses Returns a reference to the calling object

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;
}

Related articles: