Читаем C++ Primer Plus полностью

• If there are multiple constructors, all should use new the same way—either all with brackets or all without brackets. There’s only one destructor, so all constructors have to be compatible with that destructor. However, it is permissible to initialize a pointer with new in one constructor and with the null pointer (0, or, with C++11, nullptr) in another constructor because it’s okay to apply 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.

• 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.

• 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.

Memberwise Copying for Classes with Class Members

Suppose you use the String class, or, for that matter, the standard string class as a type for class members:

class Magazine

{

private:

    String title;

    string publisher;

...

};

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных