示例对左值,右值作为函数参数进行传递进行的调用,以及std::move的使用对构造函数进行调用的测试。
#include <utility>
#include <iostream>
#include <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);
}
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
|