1.概要
2.代码
#include <iostream>
#include<String>
using namespace std;
namespace T1 {
class A
{
public:
int a;
void fun() {
cout << a<<endl;
}
};
void test() {
cout << "\nDefault construction ------------------------"<<endl;
A a;
}
}
namespace T2 {
class A
{
public:
A& operator = (const A& a) {
cout << "assignment function call" << endl;
this->a = a.a;
return *this;
}
int a=0;
void fun() {
cout << a << endl;
}
};
void test() {
cout << "\nassignment function ------------------------" << endl;
A a;
A b;
b = a;
a.fun();
}
}
namespace T3 {
class A
{
public:
A& operator = (const A&& a) noexcept{
cout << "Move assignment function call" << endl;
this->a = a.a;
return *this;
}
int a = 0;
void fun() {
cout << a << endl;
}
};
void test() {
//主动移动赋值函数的调用
cout << "\nMove assignment function ------------------------" << endl;
A a;
A b;
//主动调用“移动赋值函数”
b = move(a);
a.fun();
}
}
namespace T4 {
class A
{
public:
A() = default;
A(A& a) {
this->a = a.a;
}
A& operator = (const A&& a) noexcept {
cout << "Move assignment function call" << endl;
this->a = a.a;
return *this;
}
string a = "aaaa";
void fun() {
cout << a << endl;
}
};
class B
{
public:
A toA(int v) {
A ret;
ret.a = v;
//c++98:这个返回值在98的时候是必须进行深拷贝的(因为右值无法引用)
//c++11:这里因为有移动赋值函数的存在,将这里的深拷贝变成了浅拷贝
return ret;
}
};
void test() {
//系统自动移动赋值函数的调用
cout << "\n2 Move assignment function ------------------------" << endl;
A a;
B b;
//c++11:这个右值的赋值过程,是自动的会使用“移动赋值函数”
a = b.toA(100);
a.fun();
//本质价值:右值通常只能做值传递,但是有了“移动拷贝”和“移动赋值”的存在可以对右值进行引用处理
}
}
namespace T5 {
class A
{
public:
A() = default;
A(A& a) {
this->a = a.a;
}
A(const A&& a)noexcept {
cout << "Move constructor calls" << endl;
this->a = a.a;
}
string a = "aaaa";
void fun() {
cout << a << endl;
}
};
class B
{
public:
A toA(int v) {
A ret;
ret.a = v;
//c++98:这个返回值在98的时候是必须进行深拷贝的(因为右值无法引用)
//c++11:这里因为有移动构造函数的存在,将这里的深拷贝变成了浅拷贝
return ret;
}
};
void test() {
//系统自动移动构造函数的调用
cout << "\nMove constructor calls------------------------" << endl;
B b;
//c++11:这个右值的赋值过程,是自动的会使用“移动构造函数”
A a = b.toA(100);
a.fun();
//本质价值:右值通常只能做值传递,但是有了“移动拷贝”和“移动赋值”的存在可以对右值进行引用处理
}
}
int main()
{
T1::test();
T2::test();
T3::test();
T4::test();
T5::test();
std::cout << "Hello World!\n";
}
3.运行结果
Default construction ------------------------
assignment function ------------------------
assignment function call
0
Move assignment function ------------------------
Move assignment function call
0
2 Move assignment function ------------------------
Move assignment function call
d
Move constructor calls------------------------
d
Hello World!