class A
{
private:
int* _p;
};
A ReturnValue()
{
return A();
}
A& a = ReturnValue(); // error: non-const lvalue reference to type 'A' cannot bind to a temporary of type 'A' const A& a2 = ReturnValue(); // ok
A&& a3 = ReturnValue();
#include<iostream>
class A
{
public:
A(int a)
:_p(new int(a))
{
}
// 移动构造函数 移动语义
A(A&& rhs)
: _p(rhs._p)
{
// 将临时值资源置空 避免多次释放 现在资源的归属权已经转移
rhs._p = nullptr;
std::cout<<"Move Constructor"<<std::endl;
}
// 拷贝构造函数 复制语义
A(const A& rhs)
: _p(new int(*rhs._p))
{
std::cout<<"Copy Constructor"<<std::endl;
}
private:
int* _p;
};
A ReturnValue() { return A(5); }
int main()
{
A a = ReturnValue();
return 0;
}
A a1(5); A a2 = std::move(a1);
class B
{
public:
B(B&& rhs)
: _pb(rhs._pb)
{
// how can i move rhs._a to this->_a ?
rhs._pb = nullptr;
}
private:
A _a;
int * pb;
}
template<typename T>
void Forward(T t)
{
Do(t);
}
void Do(int& i)
{
// do something...
}
template<typename T>
void Forward(const T& t)
{
Do(t);
}
int main()
{
int a = 8;
Forward(a); // error. 'void Do(int&)' : cannot convert argument 1 from 'const int' to 'int&'
return 0;
}
typedef const int T; typedef T& TR; TR& v = 1; // 在C++11中 v的实际类型为 const int&
T& + & = T& T& + && = T& T&& + & = T& T&& + && = T&&
template<typename T>
void Forward(T&& t)
{
Do(static_cast<T&&>(t));
}
void Forward(X& && t)
{
Do(static_cast<X& &&>(t));
}
void Forward(X& t)
{
Do(static_cast<X&>(t));
}
void Forward(X&& && t)
{
Do(static_cast<X&& &&>(t));
}
void Forward(X&& t)
{
Do(static_cast<X&&>(t));
}
template<typename T>
void Forward(T&& t)
{
Do(std::forward<T>(t));
}
#include<iostream>
using namespace std;
void Do(int& i) { cout << "左值引用" << endl; }
void Do(int&& i) { cout << "右值引用" << endl; }
void Do(const int& i) { cout << "常量左值引用" << endl; }
void Do(const int&& i) { cout << "常量右值引用" << endl; }
template<typename T>
void PerfectForward(T&& t){ Do(forward<T>(t)); }
int main()
{
int a;
const int b;
PerfectForward(a); // 左值引用
PerfectForward(move(a)); // 右值引用
PerfectForward(b); // 常量左值引用
PerfectForward(move(b)); // 常量右值引用
return 0;
}
template<typename T>
void Fun(T t)
{
// do something...
}
template<typename T>
void Fun(T& t)
{
// do otherthing...
}
// move
template<class _Ty>
inline typename remove_reference<_Ty>::type&& move(_Ty&& _Arg) _NOEXCEPT
{
return ((typename remove_reference<_Ty>::type&&)_Arg);
}
// forward
template<class _Ty>
inline _Ty&& forward(typename remove_reference<_Ty>::type& _Arg)
{ // forward an lvalue
return (static_cast<_Ty&&>(_Arg));
}
template<class _Ty>
inline _Ty&& forward(typename remove_reference<_Ty>::type&& _Arg) _NOEXCEPT
{ // forward anything
static_assert(!is_lvalue_reference<_Ty>::value, "bad forward call");
return (static_cast<_Ty&&>(_Arg));
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有