在C++11前,类中默认的成员函数有4个,分别是:
1.Default constructor
2.Copy constructor
3.Copy assignment operator
4.Destructor
C++11之后,又新增了两个:
5.Move Constructor
6.Move Assignment Operator
下面举一个字符串类的例子,来说明这6个函数一般是如何实现方式的:
// tstring.h
class TString {
private:
char* m_data = nullptr;
int m_length = 0;
public:
// Default constructor
TString();
// Copy constructor
TString(const TString& srcStr);
// Copy assignment operator
TString& operator=(const TString& srcStr);
// Destructor
~TString();
// Move Constructor
TString(TString&& srcStr);
// Move Assignment Operator
TString& operator=(TString&& srcStr);
//------------------------------------------
// Self-Defined constructor
TString(const char* src);
int length();
static int strlen(const char* src);
static char* strcpy(char* dst, const char* src);
};
//tsring.cpp
#include "tsring.h"
#include <cassert>
int TString::strlen(const char* src) {
int len = 0;
if (src == nullptr) {
len = 0;
}
else {
const char *temp = src;
while (*temp++ != '\0') {
len++;
}
}
return len;
};
char* TString::strcpy(char* dst, const char* src) {
assert(dst != nullptr && src != nullptr);
char* temp = dst;
while ((*temp = *src) != '\0') {
temp++;
src++;
};
return temp;
};
TString::TString(const char* src) {
if (src != nullptr) {
char *temp = new char[strlen(src) + 1];
assert(nullptr != temp);
m_data = strcpy(temp, src);
}
else {
m_data = new char[1];
assert(nullptr != m_data);
*m_data = '\0';
}
m_length = strlen(m_data);
};
int TString::length() {
return m_length;
};
//------------------------------------------
TString::TString() {
m_data = new char[1];
assert(nullptr != m_data);
*m_data = '\0';
};
TString::TString(const TString& srcStr) {
char *temp = new char[srcStr.m_length + 1];
assert(nullptr != temp);
strcpy(temp, srcStr.m_data);
m_data = temp;
m_length = srcStr.m_length;
};
TString& TString::operator=(const TString& srcStr) {
if (this == &srcStr) {
return *this;
}
char *temp = new char[srcStr.m_length + 1];
assert(nullptr != temp);
strcpy(temp, srcStr.m_data);
delete[] m_data;
m_data = temp;
m_length = srcStr.m_length;
return *this;
};
TString::~TString() {
delete[] m_data;
m_data = nullptr;
m_length = 0;
};
TString::TString(TString&& srcStr) {
m_data = srcStr.m_data;
m_length = srcStr.m_length;
srcStr.m_data = nullptr;
srcStr.m_length = 0;
};
TString& TString::operator=(TString&& srcStr) {
if (this == &srcStr) {
return *this;
}
m_data = srcStr.m_data;
m_length = srcStr.m_length;
srcStr.m_data = nullptr;
srcStr.m_length = 0;
return *this;
};
另外,需要说明的是,不存在如下形式的构造函数,因为它会造成无限递归调用,最终导致栈溢出
TString(TString srcStr);
参考文档
Constructors (C++)
C++ Rvalue References Explained
详解C++右值引用
Constructors in C++11