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

Recall that the class str member is just a pointer, so the constructor has to provide the memory for holding a string. You can pass a string pointer to the constructor when you initialize an object:

String boston("Boston");

The constructor must then allocate enough memory to hold the string, and then it must copy the string to that location. Let’s go through the process step-by-step.

First, the function initializes the len member, using the strlen() function to compute the length of the string. Next, it uses new to allocate sufficient space to hold the string, and then it assigns the address of the new memory to the str member. (Recall that strlen() returns the length of a string, not counting the terminating null character, so the constructor adds one to len to allow space for the string, including the null character.)

Next, the constructor uses strcpy() to copy the passed string into the new memory. Then it updates the object count. Finally, to help you monitor what’s going on, the constructor displays the current number of objects and the string stored in the object. This feature will come in handy later when we deliberately lead the Stringbad class into trouble.

To understand this approach, you should realize that the string is not stored in the object. The string is stored separately, in heap memory, and the object merely stores information that tells where to find the string.

Note that you do not use this:

str = s;  // not the way to go

This merely stores the address without making a copy of the string.

The default constructor behaves similarly, except that it provides a default string of "C++".

The destructor contains the example’s most important addition to the handling of classes:

StringBad::~StringBad()               // necessary destructor

{

    cout << "\"" << str << "\" object deleted, ";    // FYI

    --num_strings;                    // required

    cout << num_strings << " left\n"; // FYI

    delete [] str;                    // required

}

The destructor begins by announcing when the destructor gets called. This part is informative but not essential. However, the delete statement is vital. Recall that the str member points to memory allocated with new. When a StringBad object expires, the str pointer expires. But the memory str pointed to remains allocated unless you use delete to free it. Deleting an object frees the memory occupied by the object itself, but it does not automatically free memory pointed to by pointers that were object members. For that, you must use the destructor. By placing the delete statement in the destructor, you ensure that the memory that a constructor allocates with new is freed when the object expires.

Warning

Whenever you use new in a constructor to allocate memory, you should use delete in the corresponding destructor to free that memory. If you use new [] (with brackets), then you should use delete [] (with brackets).

Listing 12.3, which is taken from a program under development at The Daily Vegetable, illustrates when and how the StringBad constructors and destructors work. The program places the object declarations within an inner block because the destructor is called when execution exits the block in which an object is defined. Without the inner block, the destructors would be called after execution exits main(), which would prevent you in some environments from seeing the destructor messages before the execution window closes. Be sure to compile Listing 12.2 along with Listing 12.3.

Listing 12.3. vegnews.cpp

// vegnews.cpp -- using new and delete with classes

// compile with strngbad.cpp

#include

using std::cout;

#include "strngbad.h"

void callme1(StringBad &);  // pass by reference

void callme2(StringBad);    // pass by value

int main()

{

    using std::endl;

    {

        cout << "Starting an inner block.\n";

        StringBad headline1("Celery Stalks at Midnight");

        StringBad headline2("Lettuce Prey");

        StringBad sports("Spinach Leaves Bowl for Dollars");

        cout << "headline1: " << headline1 << endl;

        cout << "headline2: " << headline2 << endl;

        cout << "sports: " << sports << endl;

        callme1(headline1);

        cout << "headline1: " << headline1 << endl;

        callme2(headline2);

        cout << "headline2: " << headline2 << endl;

        cout << "Initialize one object to another:\n";

        StringBad sailor = sports;

        cout << "sailor: " << sailor << endl;

        cout << "Assign one object to another:\n";

        StringBad knot;

        knot = headline1;

        cout << "knot: " << knot << endl;

        cout << "Exiting the block.\n";

    }

    cout << "End of main()\n";

    return 0;

}

void callme1(StringBad & rsb)

{

    cout << "String passed by reference:\n";

    cout << "    \"" << rsb << "\"\n";

}

void callme2(StringBad sb)

{

    cout << "String passed by value:\n";

    cout << "    \"" << sb << "\"\n";

}

Note

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

Все книги серии 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.

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

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