简介
自己些C++代码时,总是使用最简单的C++语法,一般不会用到拷贝构造和移动构造这些比较高级的语法。但是,在读别人的C++代码时,总是被弄得晕头转向。因此,也简单学习一下。正所谓知己知彼,百战不殆。
试验代码
#include <iostream>
using namespace std;
class Class {
public:
Class() : a(""), b(""), c("") {
d = new int(0);
cout << "*** construct: " << hex << this << endl;
}
Class(const Class &cls) : a(cls.a), b(cls.b), c(cls.c) {
d = new int(0);
cout << "*** copy construct: " << hex << this << endl;
}
Class(Class &&cls) : a(cls.a), b(cls.b), c(cls.c), d(cls.d) {
cls.d = NULL;
cout << "*** move construct: " << hex << this << endl;
}
~Class() {
delete d;
cout << "### destruct: " << hex << this << endl;
}
bool compare(const Class &b) {
cout << "*** call lvalue param" << endl;
if(this->a == b.a) {
return true;
}
return false;
}
bool compare(Class &&b) {
cout << "*** call rvalue param" << endl;
if(this->a == b.a) {
return true;
}
return false;
}
public:
string a;
string b;
string c;
int *d;
};
Class getClass() {
Class x;
x.a = x.b = x.c = "test";
x.d = new int(0x14);
return x;
}
Class x;
Class &&getClassR() {
x.a = x.b = x.c = "test";
x.d = new int(0x1e);
return std::move(x);
}
int main() {
string test = "world";
Class a;
a.a = "hello";
a.b = "world";
a.c = "what";
Class b(a);
b.a = "which";
cout << "-------------------------------------------" << a.a << " " << a.b << " " << a.c << endl;
cout << "-------------------------------------------" << b.a << " " << b.b << " " << b.c << endl;
//Class c = getClass(); //call 2 move construct
Class &&c = getClass(); //call 1 move construct
c.a = "lili";
cout << "-------------------------------------------" << c.a << " " << c.b << " " << c.c << " " << *c.d << endl;
const Class d = getClassR();
cout << "-------------------------------------------" << d.a << " " << d.b << " " << d.c << " " << *d.d << endl;
cout << "-------------------------------------------" << a.compare(b) << endl;
cout << "-------------------------------------------" << a.compare(std::move(c)) << endl;
return 0;
代码解析
- 声明了一个Class类,并为Class类添加了3种构造函数。分别是:普通构造函数,拷贝构造函数和移动构造函数。
拷贝构造函数,使用类对象的左值引用作为参数。
移动构造函数,使用类对象的右值引用作为参数。
普通构造函数,无参数。 - main函数中:
2.1 Class a, 定义一个 a 对象,调用普通构造函数。
2.2 Class b(a) 定义对象 b, 此时调用拷贝构造函数。
2.3 Class &&c 定义对象 c, 此时先调用普通构造函数,创建临时对象,然后再调用移动构造函数,然后析构掉临时对象。
2.4 析构c
2.5 析构b
2.6 析构a
Makefile
all:
g++ -std=c++11 -fno-elide-constructors test.cpp -o test
注意: 编译参数中加入:-std=c++11 -fno-elide-constructors