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

This makes jolly a reference to the new structure. There is a problem with this approach: You should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() conceals the call to new, making it simpler to forget to use delete later. The auto_ptr template or, better, the C++11 unique_ptr discussed in Chapter 16, “The string Class and the Standard Template Library,” can help automate the deletion process.

Why Use const with a Reference Return?

Listing 8.6, as you’ll recall, had this statement:

accumulate(dup,five) = four;

It had the effect of first adding data from five to dup, then overwriting the contents of dup with the contents of four. Why does this statement compile? Assignment requires a modifiable lvalue on the left. That is, the subexpression on the left of an assignment expression should identify a block of memory that can be modified. In this case, the function returned a reference to dup, which does identify such a block of memory. So the statement is valid.

Regular (non reference) return types, on the other hand, are rvalues, values that can’t be accessed by address. Such expressions can appear on the right side of an assignment statement but not the left. Other examples of rvalues include literals, such as 10.0, and expressions such as x + y. Clearly, it doesn’t make sense to try to take the address of a literal such as 10.0, but why is a normal function return value an rvalue? It’s because the return value, you’ll recall, resides in a temporary memory location that doesn’t necessarily persist even until the next statement.

Suppose you want to use a reference return value but don’t want to permit behavior such as assigning a value to accumulate(). Just make the return type a const reference:

const free_throws &

    accumulate(free_throws & target, const free_throws & source);

The return type now is const, hence a nonmodifiable lvalue. Therefore, the assignment no longer is allowed:

accumulate(dup,five) = four;  // not allowed for const reference return

What about the other function calls in the program? With a const reference return type, the following statement would still be allowed:

display(accumulate(team, two));

That’s because the formal parameter for display() also is type const free_thows &. But the following statement would not be allowed because the first formal parameter for accumulate() is not const:

accumulate(accumulate(team, three), four);

Is this a great loss? Not in this case because you still can do the following:

accumulate(team, three);

accumulate(team, four);

And of course you still could use accumulate() on the right side of an assignment statement.

By omitting const, you can write shorter but more obscure-looking code.

Usually, you’re better off avoiding the addition of obscure features to a design because obscure features often expand the opportunities for obscure errors. Making the return type a const reference therefore protects you from the temptation of obfuscation. Occasionally, however, omitting const does make sense. The overloaded << operator discussed in Chapter 11, “Working with Classes,” is an example.

Using References with a Class Object

The usual C++ practice for passing class objects to a function is to use references. For instance, you would use reference parameters for functions taking objects of the string, ostream, istream, ofstream, and ifstream classes as arguments.

Let’s look at an example that uses the string class and illustrates some different design choices, some of them bad. The general idea is to create a function that adds a given string to each end of another string. Listing 8.7 provides three functions that are intended to do this. However, one of the designs is so flawed that it may cause the program to crash or even not compile.

Listing 8.7. strquote.cpp

// strquote.cpp -- different designs

#include

#include

using namespace std;

string version1(const string & s1, const string & s2);

const string & version2(string & s1, const string & s2);  // has side effect

const string & version3(string & s1, const string & s2);  // bad design

int main()

{

    string input;

    string copy;

    string result;

    cout << "Enter a string: ";

    getline(cin, input);

    copy = input;

    cout << "Your string as entered: " << input << endl;

    result = version1(input, "***");

    cout << "Your string enhanced: " << result << endl;

    cout << "Your original string: " << input << endl;

    result = version2(input, "###");

    cout << "Your string enhanced: " << result << endl;

    cout << "Your original string: " << input << endl;

    cout << "Resetting original string.\n";

    input = copy;

    result = version3(input, "@@@");

    cout << "Your string enhanced: " << result << endl;

    cout << "Your original string: " << input << endl;

    return 0;

}

string version1(const string & s1, const string & s2)

{

    string temp;

    temp = s2 + s1 + s2;

    return temp;

}

const string & version2(string & s1, const string & s2)   // has side effect

{

    s1 = s2 + s1 + s2;

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

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

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

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