c++11新特性之左值、右值、左值引用、右值引用、引用折叠、std::move()、std::forward()
参考
1.程序喵大人 2. https://zhuanlan.zhihu.com/p/461031135 https://zhuanlan.zhihu.com/p/461361869 https://zhuanlan.zhihu.com/p/461285071 https://zhuanlan.zhihu.com/p/461098279 3. https://blog.csdn.net/qq_34954047/article/details/123636179?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_title~default-5.pc_relevant_aa&spm=1001.2101.3001.4242.4&utm_relevant_index=8
实践示例:
#include <iostream>
#include <thread>
#include <future>
#include <string>
#include <functional>
void PrintV(int& t)
{
std::cout << "lvalue" << std::endl;
}
void PrintV(int&& t)
{
std::cout << "rvalue" << std::endl;
}
template<typename T>
void test1(T t)
{
PrintV(t);
}
template<typename T>
void test2(T& t)
{
PrintV(t);
}
template<typename T>
void test3(T&& t)
{
PrintV(t);
}
int main() {
int a = 2;
std::cout << "--------------------test3-----------------------" << std::endl;
test3(2);
test3(a);
test3(std::move(2));
test3(std::move(a));
test3(std::forward<int>(2));
test3(std::forward<int&&>(2));
test3(std::forward<int>(a));
test3(std::forward<int&>(a));
test3(std::forward<int&&>(a));
std::cout << "--------------------test3-----------------------" << std::endl;
std::cout << "\n\n\n\n\n\n\n\n" << std::endl;
std::cout << "--------------------test2-----------------------" << std::endl;
test2(a);
test2(std::forward<int&>(a));
std::cout << "--------------------test2-----------------------" << std::endl;
std::cout << "\n\n\n\n\n\n\n\n" << std::endl;
std::cout << "--------------------test1-----------------------" << std::endl;
test1(2);
test1(a);
test1(std::move(2));
test1(std::move(a));
test1(std::forward<int>(2));
test1(std::forward<int&&>(2));
test1(std::forward<int>(a));
test1(std::forward<int&>(a));
test1(std::forward<int&&>(a));
std::cout << "--------------------test1-----------------------" << std::endl;
std::cout << "\n\n\n\n\n\n\n\n" << std::endl;
std::cout << "--------------------lvalue-----------------------" << std::endl;
PrintV(a);
PrintV(std::forward<int&>(a));
std::cout << "--------------------lvalue-----------------------\n" << std::endl;
std::cout << "\n\n--------------------rvalue-----------------------" << std::endl;
PrintV(2);
PrintV(std::move(2));
PrintV(std::move(a));
PrintV(std::forward<int>(2));
PrintV(std::forward<int&&>(2));
PrintV(std::forward<int>(a));
PrintV(std::forward<int&&>(a));
std::cout << "--------------------rvalue-----------------------\n" << std::endl;
return 0;
}
|