6个缺省函数
构造 析构 拷贝 赋值 取地址——对普通对象取地址 对常对象取地址
C11标准 delete删掉取地址的缺省函数 在运行时就不能取地址了
移动构造
String(String&& s)
{
str = s.str;
s.str = nullptr;
}
拿返回的对象跳过将亡值对象,调动移动构建直接构建s1
移动赋值
String& operator=(String&& s)
{
if (this != &s)
{
delete[]str;
str = s.str;
s.str = nullptr;
}
return *this;
}
构造函数、拷贝构造函数、移动构造都是是创建对象,对象s2已存在,调动移动赋值函数
Return s 通过移动构造来构建临时对象,临时对象指针指向hello,fun()函数销毁,将亡值调动移动赋值,s是str别名,释放s2指向的空间
若删除移动构造 移动赋值
为s1 s2分配空间,fun()开辟栈帧,s的str指向堆区hello\0,return s调动构造函数构建临时对象,临时对象的str也指向堆区空间hello\0,fun函数结束,释放栈帧。通过将亡对象构建s1,调动拷贝构造,调动析构函数释放临时对象。