当前位置: 首页 > article >正文

【C++ 面试 - 新特性】每日 3 题(七)

✍个人博客:Pandaconda-CSDN博客
📣专栏地址:http://t.csdnimg.cn/fYaBd
📚专栏简介:在这个专栏中,我将会分享 C++ 面试中常见的面试题给大家~
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

19. 移动语义和完美转发

move

在 C++11 添加了右值引用,并且不能使用左值初始化右值引用,如果想要使用左值初始化一个右值引用需要借助 std::move () 函数,使用 std::move 方法可以将左值转换为右值。使用这个函数并不能移动任何东西,而是和移动构造函数一样都具有移动语义,将对象的状态或者所有权从一个对象转移到另一个对象,只是转移,没有内存拷贝。

从实现上讲,std::move 基本等同于一个类型转换:static_cast<T&&>(lvalue) ,函数原型如下:

template<class _Ty>
_NODISCARD constexpr remove_reference_t<_Ty>&& move(_Ty&& _Arg) _NOEXCEPT
{   // forward _Arg as movable
    return (static_cast<remove_reference_t<_Ty>&&>(_Arg));
}

使用方法如下:

class Test
{
publicTest(){}
    ......
}
int main()
{
    Test t;
    Test && v1 = t;          // error
    Test && v2 = move(t);    // ok
    return 0;
}
  • 在第 10 行中,使用左值初始化右值引用,因此语法是错误的
  • 在第 11 行中,使用 move() 函数将左值转换为了右值,这样就可以初始化右值引用了。

假设一个临时容器很大,并且需要将这个容器赋值给另一个容器,就可以执行如下操作:

list<string> ls;
ls.push_back("hello");
ls.push_back("world");
......
list<string> ls1 = ls;        // 需要拷贝, 效率低
list<string> ls2 = move(ls);

如果不使用 std::move,拷贝的代价很大,性能较低。使用 move 几乎没有任何代价,只是转换了资源的所有权。如果一个对象内部有较大的堆内存或者动态数组时,使用 move() 就可以非常方便的进行数据所有权的转移。另外,我们也可以给类编写相应的移动构造函数(T::T(T&& another))和和具有移动语义的赋值函数(T&& T::operator=(T&& rhs)),在构造对象和赋值的时候尽可能的进行资源的重复利用,因为它们都是接收一个右值引用参数。

forward

右值引用类型是独立于值的,一个右值引用作为函数参数的形参时,在函数内部转发该参数给内部其他函数时,它就变成一个左值,并不是原来的类型了。如果需要按照参数原来的类型转发到另一个函数,可以使用 C++11 提供的 std::forward() 函数,该函数实现的功能称之为完美转发。

// 函数原型
template <class T> T&& forward (typename remove_reference<T>::type& t) noexcept;
template <class T> T&& forward (typename remove_reference<T>::type&& t) noexcept;

// 精简之后的样子
std::forward<T>(t);
  • 当 T 为左值引用类型时,t 将被转换为 T 类型的左值
  • 当 T 不是左值引用类型时,t 将被转换为 T 类型的右值

下面通过一个例子演示一下关于 forward 的使用:
在这里插入图片描述

#include <iostream>
using namespace std;

template<typename T>
void printValue(T& t)
{
    cout << "l-value: " << t << endl;
}

template<typename T>
void printValue(T&& t)
{
    cout << "r-value: " << t << endl;
}

template<typename T>
void testForward(T && v)
{
    printValue(v);
    printValue(move(v));
    printValue(forward<T>(v));
    cout << endl;
}

int main()
{
    testForward(520);
    int num = 1314;
    testForward(num);
    testForward(forward<int>(num));
    testForward(forward<int&>(num));
    testForward(forward<int&&>(num));

    return 0;
}

测试代码打印的结果如下:

l-value: 520
r-value: 520
r-value: 520

l-value: 1314
r-value: 1314
l-value: 1314

l-value: 1314
r-value: 1314
r-value: 1314

l-value: 1314
r-value: 1314
l-value: 1314

l-value: 1314
r-value: 1314
r-value: 1314
  • testForward(520); 函数的形参为未定引用类型 T&& ,实参为右值,初始化后被推导为一个右值引用
    • printValue(v); 已命名的右值 v ,编译器会视为左值处理,实参为左值
    • printValue(move(v)); 已命名的右值编译器会视为左值处理,通过 move 又将其转换为右值,实参为右值
    • printValue(forward(v)); ,forward 的模板参数为右值引用,最终得到一个右值,实参为右值
  • testForward(num); 函数的形参为未定引用类型 T&& ,实参为左值,初始化后被推导为一个左值引用
    • printValue(v); 实参为左值
    • printValue(move(v)); 通过 move 将左值转换为右值,实参为右值
    • printValue(forward(v)); ,forward 的模板参数为左值引用,最终得到一个左值引用,实参为左值
  • testForward(forward(num)); ,forward 的模板类型为 int ,最终会得到一个右值,函数的形参为未定引用类型 T&& 被右值初始化后得到一个右值引用类型
    • printValue(v); 已命名的右值 v ,编译器会视为左值处理,实参为左值
    • printValue(move(v)); 已命名的右值编译器会视为左值处理,通过 move 又将其转换为右值,实参为右值
    • printValue(forward(v)); ,forward 的模板参数为右值引用,最终得到一个右值,实参为右值
  • testForward(forward<int&>(num)); ,forward 的模板类型为 int& ,最终会得到一个左值,函数的形参为未定引用类型 T&& 被左值初始化后得到一个左值引用类型
    • printValue(v); 实参为左值
    • printValue(move(v)); 通过 move 将左值转换为右值,实参为右值
    • printValue(forward(v)); ,forward 的模板参数为左值引用,最终得到一个左值,实参为左值
  • testForward(forward<int&&>(num)); ,forward 的模板类型为 int&& ,最终会得到一个右值,函数的形参为未定引用类型 T&& 被右值初始化后得到一个右值引用类型
    • printValue(v); 已命名的右值 v ,编译器会视为左值处理,实参为左值
    • printValue(move(v)); 已命名的右值编译器会视为左值处理,通过 move 又将其转换为右值,实参为右值
    • printValue(forward(v)); ,forward 的模板参数为右值引用,最终得到一个右值,实参为右值

20. 什么是 function 函数,该如何使用?

绑定器本身还是一个函数对象

function:绑定器,函数对象,lambda表达式 它们只能使用在一条语句中

体验下 function 的用法:

#include <iostream>
#include <functional>

using namespace std;

void hello1()
{
    cout << "hello" << endl;
}

void hello2(string str)
{
    cout << str << endl;
}

int sum(int a, int b)
{
    return a + b;
}

class Test
{
public: //调成员方法必须依赖一个对象 void (Test::*pfunc)(string)
    Test() { cout << "Test()" << endl; }
    void hello(string str) { cout << str << endl; }
};

int main()
{
    function<void()>func1 = hello1;
    func1();        //func1.operator() => hello1()
    function<void(string)>func2 = hello2;
    func2("hi~");        //func2.operator()(string str) => hello2(string str)
    function<int(int, int)>func3 = sum;
    cout << func3(10, 20) << endl;
    function<int(int, int)> func4 = [](int a, int b)->int {return a + b; };
    cout << func4(20, 30) << endl;
    
    function<void(Test*, string)> func5 = &Test::hello;
    func5(&Test(), "call Test::hello");

    return 0;
}
/*
hello
hi~
30
50
Test()
call Test::hello
*/

用 function + 哈希表 取代 switch:

#include <iostream>
#include <functional>
#include <map>

using namespace std;

void doA() { cout << "A" << endl; }
void doB() { cout << "B" << endl; }
void doC() { cout << "C" << endl; }

int main()
{
    map<int, function<void()>>m;
    m.insert({ 1, doA });
    m.insert({ 2, doB });
    m.insert({ 3, doC });
    while (1)
    {
        int x; cin >> x;
        auto it = m.find(x);
        if (it == m.end()) {
            cout << "无效选项" << endl;
        }
        else {
            it->second();
        }
    }

    return 0;
}

21. function 的实现原理

#include <iostream>
#include <typeinfo>
#include <string>
#include <functional>

using namespace std;

void hello(string str) { cout << str << endl; }

template<typename Fty>
class myfunction{};

template<typename R, typename A1>
class myfunction < R(A1) >
{
public:
    using PFUNC = R(*)(A1); //函数指针类型
    myfunction(PFUNC pfunc) :_pfunc(pfunc) { } //外面传进来的保存到自己的成员变量上
    R operator() (A1 arg)
    {
        return _pfunc(arg);
    }
private:
    PFUNC _pfunc;
};

template<typename R, typename A1, typename A2>
class myfunction < R(A1, A2) >
{
public:
    using PFUNC = R(*)(A1, A2); //函数指针类型
    myfunction(PFUNC pfunc) :_pfunc(pfunc) { } //外面传进来的保存到自己的成员变量上
    R operator() (A1 arg1, A2 arg2)
    {
        return _pfunc(arg1, arg2);
    }
private:
    PFUNC _pfunc;
};

int sum(int a, int b) { return a + b; }

int main()
{
    myfunction<void(string)> func1 = hello;
    func1("hello"); //func1.operator()("hello")
    myfunction<int(int, int)> func2 = sum;
    cout << func2(10, 20) << endl;
    return 0;
}

用模板语法:

#include <iostream>
#include <typeinfo>
#include <string>
#include <functional>

using namespace std;

void hello(string str) { cout << str << endl; }
int sum(int a, int b) { return a + b; }

template<typename Fty>
class myfunction{}; //要先定义模板

template<typename R, typename... A> //个数是任意的
class myfunction<R(A...)>
{
public:
    using PFUNC = R(*)(A...); //函数指针类型
    myfunction(PFUNC pfunc) :_pfunc(pfunc) { } //外面传进来的保存到自己的成员变量上
    R operator() (A... arg)
    {
        return _pfunc(arg...);
    }
private:
    PFUNC _pfunc;
};

int main()
{
    myfunction<void(string)> func1 = hello;
    func1("hello"); //func1.operator()("hello")
    myfunction<int(int, int)> func2 = sum;
    cout << func2(10, 20) << endl;
    return 0;
}

http://www.kler.cn/a/297504.html

相关文章:

  • 音波效果(纯CSS实现)
  • LeetCode之区间
  • Gin-封装自动路由
  • 计算机毕业设计Pyhive+Spark招聘可视化 职位薪资预测 招聘推荐系统 招聘大数据 招聘爬虫 大数据毕业设计 Hadoop Scrapy
  • 数学建模笔记—— 线性规划
  • Chapter 11 脚手架Vue CLI使用步骤
  • PyTorch维度操作的函数介绍
  • linux高级学习12
  • 运维学习————Zabbix监控框架(1)
  • 高级算法设计与分析 学习笔记3 哈希表
  • LaTeX中算法环境横线/宽度调整(Algorithm)
  • 收银系统源码-收银台(exe、apk安装包)自由灵活操作简单!
  • 【阿雄不会写代码】全国职业院校技能大赛GZ036第五套
  • HTTP1.0 到 HTTP3.0 的优化
  • 【网络安全 | 渗透工具】IIS 短文件名枚举工具—shortscan安装使用教程
  • @Transactional 参数详解
  • Charles - 夜神模拟器证书安装App抓包-charles监控手机出现unknown 已解决
  • 子网ip和ip地址一样吗?子网ip地址怎么算
  • Google AI 概述——喜欢的三点和不喜欢的两点
  • 使用Python海龟绘图画出奥运五环图