64,642
社区成员
发帖
与我相关
我的任务
分享
struct test_stru
{
test_stru(){}
test_stru(test_stru&& tt)
{
x = tt.x;
y = tt.y;
}
int x;
int y;
};
test_stru test_r_struct() //一般我们都说不要返回局部对象的引用(左值),现在用右值好象没什么问题?
{
test_stru tt;
tt.x = 10;tt.y = 10;
return tt;
}
void test_print_stru(test_stru&& tt)
{
std::cout<<tt.x<<" "<<tt.y<<std::endl;
};
.....
//test_stru&& f = test_r_struct();
//test_print_stru(f); //这样用是错误的,cannot convert parameter 1 from 'test_stru' to 'test_stru &&'
难道定义的右值引用f不能直接传给函数?还是编译器自动的把它退化成了一个普通的右值变量?
test_print_stru(test_r_struct());//这样OK
std::vector<int>&& test_refer_vec()
{
std::vector<int> vec;
for (int i=1; i<10; ++i)
{
vec.push_back(i);
}
return std::move(vec);
}
template <class T>
T&& moves(T&& a)
{
return a;
}
template <class T> void swaps(T& a, T& b)
{
T tmp(moves(a)); 为什么moves返回的是一个右值引用,在这里可以做实参呢?
a = moves(b);
b = moves(tmp);
}
std::vector<int> test_refer_vec()
{
std::vector<int> vec;
for (int i=1; i<10; ++i)
{
vec.push_back(i);
}
return std::move(vec);
}
..............
std::vector<int>&& tt = test_refer_vec();
#include<stdio.h>
#include<utility>
using namespace std;
struct test
{
int n;
test():n(1)
{
puts( "test::test" );
}
~test()
{
puts( "test::~test" );
}
};
//*
test && operator+( const test& l, test && r)
{
r.n += l.n;
return move( r );
}//*/
test operator+( const test& l , const test& r)
{
test x;
x.n = l.n + r.n;
return x;
}
int main()
{
test a;
test b = a + test() + test() + test();
printf("%d\n" , b.n );
}
比较 注释掉test && operator+( const test& l, test && r)和不注释就能看出效率的差别了。
test_stru operator= (test_stru&& tt)
{
this->x = tt.x;
this->y = tt.y;
return *this;
}