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

// safe to return reference passed to function

    return s1;

}

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

{

    string temp;

    temp = s2 + s1 + s2;

// unsafe to return reference to local variable

    return temp;

}

Here is a sample run of the program in Listing 8.7:

Enter a string: It's not my fault.

Your string as entered: It's not my fault.

Your string enhanced: ***It's not my fault.***

Your original string: It's not my fault.

Your string enhanced: ###It's not my fault.###

Your original string: ###It's not my fault.###

Resetting original string.

At this point the program crashed.

Program Notes

Version 1 of the function in Listing 8.7 is the most straightforward of the three:

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

{

    string temp;

    temp = s2 + s1 + s2;

    return temp;

}

It takes two string arguments and uses string class addition to create a new string that has the desired properties. Note that the two function arguments are const references. The function would produce the same end result if it just passed string objects:

string version4(string s1, string  s2)  // would work the same

In this case, s1 and s2 would be brand-new string objects. Thus, using references is more efficient because the function doesn’t have to create new objects and copy data from the old objects to the new. The use of the const qualifier indicates that this function will use, but not modify, the original strings.

The temp object is a new object, local to the version1() function, and it ceases to exist when the function terminates. Thus, returning temp as a reference won’t work, so the function type is string. This means the contents of temp will be copied to a temporary return location. Then, in main(), the contents of the return location are copied to the string named result:

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

Passing a C-Style String Argument to a string Object Reference Parameter

You may have noticed a rather interesting fact about the version1() function: Both formal parameters (s1 and s2) are type const string &, but the actual arguments (input and "***") are type string and const char *, respectively. Because input is type string, there is no problem having s1 refer to it. But how is it that the program accepts passing a pointer-to-char argument to a string reference?

Two things are going on here. One is that the string class defines a char *-to-string conversion, which makes it possible to initialize a string object to a C-style string. The second is a property of const reference formal parameters that is discussed earlier in this chapter. Suppose the actual argument type doesn’t match the reference parameter type but can be converted to the reference type. Then the program creates a temporary variable of the correct type, initializes it to the converted value, and passes a reference to the temporary variable. Earlier this chapter you saw, for instance, that a const double & parameter can handle an int argument in this fashion. Similarly, a const string & parameter can handle a char * or const char * argument in this fashion.

The convenient outcome of this is that if the formal parameter is type const string &, the actual argument used in the function call can be a string object or a C-style string, such as a quoted string literal, a null-terminated array of char, or a pointer variable that points to a char. Hence the following works fine:

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

The version2() function doesn’t create a temporary string. Instead, it directly alters the original string:

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

{

    s1 = s2 + s1 + s2;

// safe to return reference passed to function

    return s1;

}

This function is allowed to alter s1 because s1, unlike s2, is not declared using const.

Because s1 is a reference to an object (input) in main(), it’s safe to return s1 as a reference. Because s1 is a reference to input, the line

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

essentially becomes equivalent to the following:

version2(input, "###");     // input altered directly by version2()

result = input;             // reference to s1 is reference to input

However, because s1 is a reference to input, calling this function has the side effect of altering input also:

Your original string: It's not my fault.

Your string enhanced: ###It's not my fault.###

Your original string: ###It's not my fault.###

Thus, if you want to keep the original string unaltered, this is the wrong design.

The third version in Listing 8.7 is a reminder of what not to do:

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

{

    string temp;

    temp = s2 + s1 + s2;

// unsafe to return reference to local variable

    return temp;

}

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

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

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

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