C++--string class and Standard Template Library

Source: Internet
Author: User

First, the String class

 1. Constructor function

The string is actually a typedef of the basic_string<char> and omits parameters related to memory management. Size_type is an implementation-dependent integral type that is defined in string. The string class defines string::npos as the maximum length of a string, usually the maximum value of unsigned int. In addition, use the abbreviation Nbts (null-terminated string) to represent a string ending with a null character-the traditional C string. The constructor for string is listed in the following table:

constructor function Describe
string (const char * s) Initializes a string object to an S-pointing nbts
String (size_type N, char c) Creates a string object that contains n elements, where each element is initialized to the character C
String (const string & str) Initializes a string object to a String object, str (copy constructor)
String () Creates a default string object with a length of 0 (default constructor)
string (const char * s,size_type N) Initializes a string object to the first n characters of the Nbts pointed by S, even if the nbts end is exceeded

Template<class iter>

String (Iter Begin,iter end)

Initializes a string object to a character within the interval [begin,end], where begin and end behaves like a pointer, for specifying a position, including the begin, but not including the end
String (const string & str, size_type pos = 0,size_type n = NPOs) Initializes a string object to the character from position Pos to the end of the object Str, or n characters starting from position POS
String (String && str) noexcept This is c++11 new, he initializes a string object to the String object str, and may modify STR (move constructor)
String (initializer_list<char> il) This is c++11 new, which initializes a string object to the character in the initialization list IL

2, String class input

For classes, you need to know which input methods are available. There are 3 ways to type a C-style string:
Char info[100];

CIN >> info;//Read a word

Cin.getline (info,100);//reads a line, encounters \ nthe end, and discards \ n

Cin.get (info, 100);//reads a line, encounters \ n ends, discards \ nthe input queue

For string objects, there are two ways of doing this:

string stuff;

CIN >> stuff;//Read a word

Getline (Cin,stuff);//read one line, encounter \ n end and discard \ n

Second, smart pointer template class

A smart pointer is a class object that behaves like a pointer.

Auto_ptr is the solution provided by c++98, C++11 has abandoned it and offers two other solutions. However, although Auto_ptr is abandoned, it has been used for years, and if the compiler does not support the other two solutions, Auto_ptr will be the only solution.

2.1. Using smart pointers

The three smart pointer templates, Auto_ptr, Unique_ptr, and shared_ptr, define pointers-like objects that can be assigned new (direct or indirect) addresses to such objects. When a smart pointer expires, its destructor uses Delete to free memory. Therefore, if you assign the address returned by new to these objects, you do not have to remember to release the memory later: when the smart pointer expires, these saves are automatically freed.

To create a smart pointer object, you must include the header file memory, which is defined by the file template. Then use the usual template syntax to instantiate a pointer of the desired type. For example, the template auto_ptr contains the following constructors:

Template<class X> class auto_ptr{

Public

Explicit Auto_ptr (X *p = 0) throw ();

...};

throw () means that the constructor does not throw an exception and, like Auto_ptr, throw () is discarded. Therefore, a auto_ptr that requests an X type will get a auto_ptr that points to the X type:

Auto_ptr<double> PD (new double);

Auto_ptr<string> PS (new string);

The new double is a pointer to the newly allocated memory block. It is the argument of the constructor auto_ptr<double>, which corresponds to the argument p in the prototype. Similarly, the new string is also an argument to the constructor. The other two kinds of smart pointers use the same syntax:
Unique_ptr<double> PDU (new double);

Shared_ptr<string> PSS (new string);

The smart pointer template is located in the namespace Std. The following program shows how to use all three smart pointers. Each smart pointer is placed within the same block of code, so the pointer expires when you leave the code. The report class uses methods for reporting object creation and destruction.

1#include <iostream>2#include <memory>3 4 classreport{5 Private:6STD::stringstr;7  Public:8Report (ConstSTD::string&s): Str (s) {9Std::cout <<"The object was created"<< Str <<"! \ n";Ten     } One~Report () { AStd::cout <<"objects are destroyed"<< Str <<"! \ n"; -     } -     voidComment ()Const{ theStd::cout << str <<"\ n"; -     } - }; -  + intMainintargcChar*argv[]) - { +     using namespacestd; A     { atAuto_ptr<report> PS (NewReport ("using Auto_ptr")); -Ps->comment (); -     } -     { -Shared_ptr<report> PS (NewReport ("using shared_ptr")); -Ps->comment (); in     } -     { toUnique_ptr<report> PS (NewReport ("using Unique_ptr")); +Ps->comment (); -     } the     return 0; * } $ Panax Notoginseng Output Result: - object using auto_ptr! was created  the usingauto_ptr +Object using auto_ptr! was destroyed A object using shared_ptr! was created  the usingshared_ptr +Object using shared_ptr! was destroyed - object using unique_ptr! was created  $ usingunique_ptr $Object using unique_ptr! was destroyed

All smart pointers have a explicit constructor that takes the pointer as a parameter. Therefore, you do not need to automatically convert the pointer to a smart pointer object.

Because of how smart pointer templates are defined, many aspects of smart pointer objects are similar to regular pointers.

2.2. Precautions for smart pointers

Why use three kinds of smart pointers? There are actually 4 kinds, the other is weak_ptr, but we don't discuss it. Why Abandon Auto_ptr?

First look at the following copy statement:

Std::auto_ptr<std::string> PS (New std::string ("Good morning!"));

std::auto_ptr<std::string> Vocation;

Vocation = PS;

What do the above assignment statements do? If PS and vocation are regular pointers, two pointers will point to the same string object. This is unacceptable because the program removes the view from the same object two times-one time when PS expires, and the other when vocation expires. There are several ways to avoid this problem.

* Define the assignment operator so that it performs deep replication. This way two pointers will point to different objects, one of which is a copy of the other object.

* Establish the concept of ownership (ownership), for a specific value, only one smart pointer can have it, so that only the destructor that owns the smart pointer to the object will delete the object. Then, let the assignment action transfer ownership. This is the strategy for auto_ptr and Unique_ptr, but Unique_ptr's strategy is stricter.

* Create smart, higher pointers that track the number of smart pointers that reference specific objects. This is called a reference count (reference counting). For example, when assigning a value, the count will be 1, and when the pointer expires, the count will be reduced by 1. The delete is called only when the last pointer expires. This is the strategy adopted by shared_ptr.

Of course, the same strategy applies to copy constructors as well.

Each of these methods has a purpose. The following list of programs is an example that is not suitable for auto_ptr:

#include <iostream>#include<memory>#include<string>intMainintargcChar*argv[]) {    using namespacestd; Auto_ptr<string> films[5] ={auto_ptr<string> (New string("Kaka West")), Auto_ptr<string> (New string("Adjuvant Assistance")), Auto_ptr<string> (New string("Woo-wise Ferret")), Auto_ptr<string> (New string("Kay")), Auto_ptr<string> (New string("Ning Times"))    }; Auto_ptr<string>Pwin; Pwin= films[2];  for(inti =0; I <5; i++) {cout<< *films[i] <<Endl; } cout<< *pwin <<Endl; Cin.Get(); return 0;} Output result: Cacassizzo (LLDB)//the program crashed.

The reason for the program crash is that the following statement transfers ownership from FILM[2] to Pwin:

Pwin = films[2]; FILMS[2] Lost ownership

This causes films[2] to no longer reference the string. After auto_ptr discards the ownership of an object, it may be used to ask the object. When the program prints a string that films[2] points to, it finds that this is a null pointer.

If you replace auto_ptr with shared_ptr in the above program manifest, the program runs normally:

1#include <iostream>2#include <memory>3#include <string>4 5 intMainintargcChar*argv[])6 {7     using namespacestd;8shared_ptr<string> films[5] = {9auto_ptr<string> (New string("Kaka West")),Tenauto_ptr<string> (New string("Adjuvant Assistance")), Oneauto_ptr<string> (New string("Woo-wise Ferret")), Aauto_ptr<string> (New string("Kay")), -auto_ptr<string> (New string("Ning Times")) -     }; theshared_ptr<string>Pwin; -Pwin = films[2]; -      -      for(inti =0; I <5; i++) { +cout << *films[i] <<Endl; -     } +cout << *pwin <<Endl; ACin.Get(); at     return 0; - } -  - Output Result: - Kaka West - Adjuvant Assistance in Woo-wise Ferret - Kay to Ning Times +Woo-wise Ferret

This time Pwin and films[2] point to the same object, and the reference count increases from 1 to 2. At the end of the program, the declared Pwin first calls its destructor, which reduces the reference count to 1. The members of the shared_ptr array are then freed, and when the destructor is called on films[2], the reference count is lowered to 0 and the previously allocated space is freed.

Unique_ptr, like Auto_ptr, also employs a proprietary model. However, when using UNIQUE_PTR, the program does not wait for the run phase to crash, and an error occurs during the compile phase.

  

C++--string class and Standard Template Library

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.