参考 https://www.ibm.com/developerworks/cn/aix/library/1307_lisl_c11/
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
int a = 1;
class MyString {
private:
char* _data;
size_t _len;
int b;
void _init_data(const char* s) {
_data = new char[_len + 1];
memcpy(_data, s, _len);
_data[_len] = '\0';
}
public:
MyString() {
_data = NULL;
_len = 0;
b = a++;
std::cout << "() Constructor is called! no source!"
<< ", b:" << b << std::endl;
}
MyString(const char* p) {
_len = strlen(p);
_init_data(p);
b = a++;
std::cout << "const char* Constructor is called! source: "
<< p << ", b:" << b << std::endl;
}
MyString(const MyString& str) {
_len = str._len;
_init_data(str._data);
b = a++;
std::cout << "Copy Constructor is called! source: "
<< str._data << ", b:" << b << std::endl;
}
MyString& operator=(const MyString& str) {
if (this != &str) {
_len = str._len;
_init_data(str._data);
}
std::cout << "Copy Assignment is called! source: "
<< str._data << ", b:" << b << std::endl;
return *this;
}
virtual ~MyString() {
const char* o = _data;
if (o == nullptr) {
o = "null";
}
std::cout << "Desconstructor! source: "
<< o << ", b:" << b << std::endl;
if (_data) free(_data);
}
};
int main() {
MyString a;
a = MyString("Hello");
std::vector<MyString> vec;
vec.push_back(MyString("World"));
}
输出:
() Constructor is called! no source!, b:1
const char* Constructor is called! source: Hello, b:2
Copy Assignment is called! source: Hello, b:1
Desconstructor! source: Hello, b:2
const char* Constructor is called! source: World, b:3
Copy Constructor is called! source: World, b:4
Desconstructor! source: World, b:3
Desconstructor! source: World, b:4
Desconstructor! source: Hello, b:1
增加转移构造和转移赋值
MyString(MyString&& str) {
b = a++;
std::cout << "Move Constructor is called! source: "
<< str._data << ", b:" << str.b << " to " << b << std::endl;
_len = str._len;
_data = str._data;
str._len = 0;
str._data = NULL;
}
MyString& operator=(MyString&& str) {
std::cout << "Move Assignment is called! source: "
<< str._data << ", b:" << str.b << " to " << b << std::endl;
if (this != &str) {
_len = str._len;
_data = str._data;
str._len = 0;
str._data = NULL;
}
return *this;
}
输出:
() Constructor is called! no source!, b:1
const char* Constructor is called! source: Hello, b:2
Move Assignment is called! source: Hello, b:2 to 1
Desconstructor! source: null, b:2
const char* Constructor is called! source: World, b:3
Move Constructor is called! source: World, b:3 to 4
Desconstructor! source: null, b:3
Desconstructor! source: World, b:4
Desconstructor! source: Hello, b:1
一些参考
https://zhuanlan.zhihu.com/p/99524127
左值 ,一个 lvalue 是通常可以放在等号左边的表达式
右值 ,一个 rvalue 是通常只能放在等号右边的表达式
广义左值 ,一个 glvalue 是 generalized lvalue
将亡值 ,一个 xvalue 是 expiring lvalue
纯右值,一个 prvalue 是 pure rvalue