1. 拷贝控制成员
五个用来控制拷贝控制操作的类的成员函数:析构函数、拷贝构造函数/拷贝赋值运算符、移动构造函数/移动赋值运算符
{挨个介绍:
- 形式
- 完成的操作
- 定义时注意事项(noexcept等)
- 在用户代码中,何时调用哪个(测试代码)
}
2. 合成版本的拷贝控制成员
五个拷贝控制成员,一定情况下,编译器会自动合成默认的版本:合成析构函数、合成拷贝构造函数/合成拷贝赋值运算符、合成移动构造函数/合成移动赋值运算符
{挨个介绍:
- 默认的操作语义(内置类型的移动、标准库类型的移动:测试代码)
- 何时会提供合成的版本
- 怎样强制让他合成(default)
- 怎样强制让他不合成(delete)
}
3. swap与赋值运算符
{
- 交换操作(swap、std::swap)
- 拷贝并交换(拷贝赋值运算符)
- 移动并交换(移动赋值运算符)
- 移动/拷贝赋值运算符的统一实现
}
4. 左值、右值,左值引用、右值引用
左值、右值:
{
- 什么意思;
- 哪些是左值哪些是右值;
- 特征。
}
左值引用、右值引用:
{
- 什么意思;
- 干啥用的;
- 其他
}
附:测试代码
class Foo2 {
public:
Foo2(int a, int b, string c = "") :x(a), y(b), s(string(c)), ps(new string(c)) { cout << "构造函数"<<x << endl; }
Foo2(const Foo2&);
Foo2& operator=(const Foo2&) = default;
Foo2(Foo2&&) noexcept;
Foo2& operator=(Foo2&&) noexcept = default;
~Foo2();
int x = 42;
int y = 12;
string s;
string* ps;
};
Foo2::Foo2(const Foo2& f) :x(f.x), y(f.y), s(f.s),ps(new string(*f.ps))
{
cout << "拷贝构造函数" << x << endl;
}
Foo2::Foo2(Foo2&& f) noexcept:x(std::move(f.x)), y(std::move(f.y)), s(std::move(f.s))
{
ps = f.ps;
f.ps = nullptr;
cout << "移动构造函数" << x << endl;
}
Foo2::~Foo2()
{
delete ps;
cout << "析构函数" << x << endl;
}
Foo2 func(Foo2 f) {
return f;
}
int main()
{
Foo2 fv1 = func(Foo2(11, 12, "g"));
cout << "==========" << endl;
Foo2 fv2 = func(std::move(Foo2(13, 14, "g")));
cout << "==========" << endl;
Foo2 v2(26, 12, "s");
cout << "7:" << v2.x << "," << v2.y << "," << v2.s << "," << *v2.ps << endl;//26,12,s,s
Foo2 mv2(std::move(v2));//移动构造函数
cout << "8:" << v2.x <<","<< v2.y << "," << v2.s << "," << v2.ps << endl;//26,12,,00000000
cout << "9:" << mv2.x << "," << mv2.y << "," << mv2.s << "," << *mv2.ps << endl;//26,12,s,s
mv2.x = 10; mv2.y = 20; mv2.s = "a"; *mv2.ps = "a";
cout << "10:" << v2.x << "," << v2.y << "," << v2.s << "," << v2.ps << endl;//26,12,,00000000 //指针移动只移动指针本身的值,同其他内置类型一样
cout << "11:" << mv2.x << "," << mv2.y << "," << mv2.s << "," << *mv2.ps << endl;//10,20,a,a
cout << "==========" << endl;
Foo2 fv3 = func(mv2);
cout << "==========" << endl;
/*再测试一次v2和mv2是否因为func调用而改变*/
cout << "10:" << v2.x << "," << v2.y << "," << v2.s << "," << v2.ps << endl;//26,12,,00000000
cout << "11:" << mv2.x << "," << mv2.y << "," << mv2.s << "," << *mv2.ps << endl;//10,20,a,a
/*验证内置类型的移动*/
int i = 1;
int j(i);
int k(std::move(i));
cout << i << j << k << endl;
k = 2;
cout << i << j << k << endl;
i = 3;
cout << i << j << k << endl;
/*验证标准库类型的移动*/
string s = "abc";
string ss(std::move(s));
cout << s << endl;//s置为空
cout << ss << endl;//ss存着原来s中的字符
vector<int> vec(10, 1);
for (auto v : vec)
cout << v;
cout << endl;
vector<int> vec2(std::move(vec));
for (auto v : vec)
cout << v;
cout << endl;
for (auto v : vec2)
cout << v;
cout << endl;
return 0;
}