Share the correct writing of string class in C + + interview _c language

Source: Internet
Author: User

In specific terms:

You can define variables like the int type and support assignment and replication.
Can be used as the parameter type and return type of a function.
A type of element that can be used as a standard reservoir, that is, a vector/list/deque value_type. (used as a std::map key_type is a further requirement, this article Conlio).
In other words, your String allows the following code to compile and run through without any memory errors.

Copy Code code as follows:

void foo (String x)
{
}

void Bar (const string& x)
{
}

String Baz ()
{
String ret ("World");
return ret;
}

int main ()
{
String S0;
String S1 ("Hello");
String S2 (S0);
String s3 = S1;
s2 = S1;

Foo (s1);
Bar (S1);
Foo ("temporary");
Bar ("temporary");
String S4 = Baz ();

Std::vector<string> Svec;
Svec.push_back (S0);
Svec.push_back (S1);
Svec.push_back (Baz ());
Svec.push_back ("Good job");
}

This article gives me the answer that I think is suitable for the interview, emphasize correctness and easy to realize (the Whiteboard is not wrong to write), do not emphasize efficiency. In a sense, it can be said that the time (speed) of space (code concise).

First select the data member, the simplest String has only one char* member variable. The benefits are easy to implement, and the downside is that some operations are more complex (such as size () will be linear time). There is only one char* Data_ member of the String designed for the interview to write code without error. and the rules invariant as follows: A valid string object's Data_ guarantee does not end with ' the ' for Null,data_, in order to facilitate the str* () series functions of the C language.

Second, decide which operations to support, construction, deconstruction, copy construction, assignment of these things are certain (formerly known as the Big Three, now called Copy control). If you drill deeper, C++11 's move construction and move assignments can also be available. In order to highlight the focus, this article does not consider operator[] such as the overload.

So the code is basically stereotyped:

Copy Code code as follows:

#include <utility>
#include <string.h>

Class String
{
Public
String ()
: Data_ (new char[1])
{
*data_ = ' n ';
}

String (const char* STR)
: Data_ (new Char[strlen (str) + 1])
{
strcpy (Data_, str);
}

String (const string& RHS)
: Data_ (New Char[rhs.size () + 1])
{
strcpy (Data_, Rhs.c_str ());
}
/* Delegate Constructor in c++11
String (const string& RHS)
: String (Rhs.data_)
{
}
*/

~string ()
{
Delete[] Data_;
}

/* Traditional:
string& operator= (const string& RHS)
{
String tmp (RHS);
Swap (TMP);
return *this;
}
*/
string& operator= (String RHS)/Yes, Pass-by-value
{
Swap (RHS);
return *this;
}

C + + 11
String (string&& RHS)
: Data_ (Rhs.data_)
{
Rhs.data_ = nullptr;
}

string& operator= (string&& RHS)
{
Swap (RHS);
return *this;
}

Accessors

size_t size () const
{
return strlen (Data_);
}

Const char* C_STR () const
{
return data_;
}

void swap (string& rhs)
{
Std::swap (Data_, Rhs.data_);
}

Private
char* Data_;
};

Note the several points of the code:

Call new char[only in the constructor, call delete[in the destructor only.
The assignment operator uses the modern notation recommended by the C + + programming specification.
Each function has only one or two lines of code, no condition to judge.
The destructor does not have to check whether Data_ is NULL.
Constructor String (const char* str) does not check the legality of STR, which is a never-ending topic of contention. This is where STR is used in the initialization list, so it is meaningless to use ASSERT () in the function body.
This is probably the most concise String implementation.

Exercise 1: Add operator==, operator<, operator[] and other operator overloads.

Exercise 2: Implement a band int size_; The version of the member, in space to change time.

Exercise 3: Benefit from the right value reference and mobile semantics, in c++11, the performance of the direct insertion sort of String is higher than the C++98/03, test programming verification. (g++ 's standard library also uses this technique.) )

Chenhao Note: At the same time, you can go to see my old article, "The Problem of string in STL"

Original link: http://coolshell.cn/articles/10478.html

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.