Recently implemented a string class, adding some c ++ 11 elements.
In addition to basic constructor, copy constructor, and assign value function, you can also add mobile copy and assign value functions. Default is a convenient feature.
//default constructorKianString()=default;KianString(const char *c): ch_(0) { ch_ = (char*)malloc(sizeof(char)*(strlen(c)+1)); strncpy(ch_, c, strlen(c)+1);};~KianString(){ free(ch_);}//copy constructorKianString(const KianString &str){ ch_ = (char*)malloc(sizeof(char)*(str.size()+1)); strncpy(ch_, str.ch_, str.size()+1);}//assign operator, is ok for both lvalue and rvalue!KianString &operator=(KianString str) noexcept { swap(*this, str); return *this;}//move constructorKianString(KianString &&str) noexcept : ch_(str.ch_) {str.ch_ = NULL;}
Copy and swap idiom are used for value assignment copying:
inline void swap(KianString &str1, KianString &str2){ using std::swap; swap(str1.ch, str2.ch);}//assign operator, is ok for both lvalue and rvalue! KianString &operator=(KianString str) noexcept { swap(*this, str); return *this;}
There are several advantages to doing so:
1. the parameter is a value transfer call. You can use both the left and right values. When the right value is used, the mobile copy function is automatically called.
2. Strong exceptions and security. exceptions only occur when the parameter is copied. If an exception occurs, this is not affected.
3. The value transfer generates a copy, so the auto-assigned value is correct.
Addition operator overload:
KianString &operator+=(const KianString &str){ ch = (char*)realloc(ch, strlen(ch)+str.size()+1); strcat(ch, str.ch); return *this;}template<typename T>
const T operator+(const T& lhs, const T& rhs) {
return T(lhs) += rhs;
}
1. According to article 3 of "c ++ programming specifications", to implement the + operator, we must first implement the ++ = operator, and ensure semantic consistency for easy maintenance.
2. operator + is defined as a non-member function and can accept implicit conversion between left and right parameters at the same time. Because operator + = is public, operator + does not need to be set to friend.
3. Define operator + as template.
Code:
Https://github.com/coderkian/kianstring