A correct way of writing string class in C + + interview

Source: Internet
Author: User

A common interview question for C + + is to allow you to implement a String class that is limited to time and cannot require std::string functionality, but at least requires that resources be managed correctly. Specifically:

    1. Variables can be defined like the int type, and assignments and replications are supported.
    2. The type and return type of the parameter that can be used as a function.
    3. The element type that can be used as a standard reservoir, i.e. the value_type of Vector/list/deque. (The Key_type used as std::map is a further requirement, this article withheld).

In other words, your String allows the following code to compile and run through, and there are no memory errors.

voidfoo (String x) {}voidBarConststring&x) {} string Baz () {string ret (" World"); returnret;} intMain () {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 the answer I think is suitable for the interview, emphasizing correctness and easy implementation (the Whiteboard is not wrong to write), do not emphasize efficiency. In a sense it can be said that the time (running speed) to change space (code concise).

First, the data member is selected, and 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 (for example, size () is linear time). In order to write code in the interview without error, this article designed a String with only one char* Data_ member. and the provisions invariant as follows: A valid string object Data_ guaranteed not to end with Null,data_ ‘\0‘ , to facilitate the use of the C-language str* () series functions.

The next decision to support what operations, construction, destruction, copy construction, assignment is sure to have some (formerly known as the Big Three, now called Copy control). If you drill a bit deeper, you can also have c++11 movement and movement assignments. In order to highlight the focus, this article does not consider operator[] and other overloads.

So the code is basically stereotyped:

#include <utility>#include<string.h>classstring{ Public: String (): Data_ (New Char[1])  {    *data_ =' /'; } String (Const Char*str): Data_ (New Char[Strlen (str) +1]) {strcpy (Data_, str); } String (Conststring&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 + +String (string&&RHS): Data_ (rhs.data_) {Rhs.data_=nullptr; } String&operator= (string&&RHS)    {Swap (RHS); return* This; }   //Accessorssize_t size ()Const  {    returnstrlen (Data_); }   Const Char* C_STR ()Const  {    returnData_; }   voidSwap (string&RHS)  {Std::swap (Data_, Rhs.data_); }  Private:  Char*Data_;};

Note Several key points of the code:

    1. Call new char[] only in the constructor, call delete[] in the destructor only.
    2. The assignment operator uses the modern notation recommended by the C + + programming specification.
    3. Each function has only one or two lines of code, and there is no condition to judge.
    4. Destructors do not have to check if Data_ is NULL.
    5. The constructor String(const char* str) does not check the legality of STR, which is a never-ending debate topic. STR is used here 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 overloads such as operator==, operator<, operator[].

Exercise 2: Implement an int size_; The version of the member, with space to change time.

Exercise 3: benefit from rvalue references and moving semantics, the performance of direct insertion ordering of String in c++11 is higher than that of c++98/03, and the test program validates it. (The g++ standard library also uses this technique.) )

A correct way of writing string class in C + + interview

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.