示例对左值,右值作为函数参数进行传递进行的调用,以及std::move的使用对构造函数进行调用的测试。
- 测试示例
#include <utility> // std::move
#include <iostream> // std::cout
#include <vector> // std::vector
#include <string>
class Myclass{
public:
explicit Myclass(int value) : val(value){
std::cout<<"construct"<<std::endl;
}
Myclass(const Myclass& value){
std::cout<<"copy"<<std::endl;
}
Myclass(Myclass&& value){
std::cout<<"move"<<std::endl;
}
void operator = (Myclass& value){
std::cout<<"operator = l reference"<<std::endl;
}
void operator = (Myclass&& value){
std::cout<<"operator = r reference"<<std::endl;
}
~Myclass(){
std::cout<<"deconstruct"<<std::endl;
}
private:
int val;
};
//两个重载函数:左值引用和右值引用
void test_01(Myclass&& val){
std::cout<<"test_01 rvalue reference"<<std::endl;
}
void test_01(const Myclass& val){
std::cout<<"test_01 lvalue reference"<<std::endl;
}
//直接调用右值引用
void MyclassTest1(){
std::cout<<"MyclassTest1-----------------"<<std::endl;
Myclass val1(10);
test_01(std::move(val1));
}
//调用该类的移动构造函数
void MyclassTest2(){
std::cout<<"MyclassTest2-----------------"<<std::endl;
Myclass val1(10);
Myclass val2 = std::move(val1);
}
//左值引用和右值引用都会当作一个左值来传参
void MyclassTest3(){
std::cout<<"MyclassTest3-----------------"<<std::endl;
Myclass val1(10);
Myclass&& val2 = std::move(val1);
test_01(val2);
}
void MyclassTest4(){
std::cout<<"MyclassTest4-----------------"<<std::endl;
Myclass val1(10);
Myclass& val2 = val1;
test_01(val2);
}
//该测试函数测试test_01的优先级调用问题
void MyclassTest5(){
std::cout<<"MyclassTest5-----------------"<<std::endl;
Myclass val1(10);
test_01(std::move(val1));
}
//赋值构造函数调用
void MyclassTest6(){
std::cout<<"MyclassTest6-----------------"<<std::endl;
Myclass val1(10);
Myclass val2(20);
val2 = std::move(val1);
}
int main(){
MyclassTest1();
MyclassTest2();
MyclassTest3();
MyclassTest4();
MyclassTest5();
MyclassTest6();
return 0;
}
- 测试结果:
MyclassTest1-----------------
construct
test_01 rvalue reference
deconstruct
MyclassTest2-----------------
construct
move
deconstruct
deconstruct
MyclassTest3-----------------
construct
test_01 lvalue reference
deconstruct
MyclassTest4-----------------
construct
test_01 lvalue reference
deconstruct
MyclassTest5-----------------
construct
test_01 rvalue reference
deconstruct
MyclassTest6-----------------
construct
construct
operator = r reference
deconstruct
deconstruct