Modern C++——函数参数类型的分类和使用

2024-08-28 08:20

本文主要是介绍Modern C++——函数参数类型的分类和使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

大纲

  • 基本定义
  • 值类型
  • 左值引用
    • 非常量左值引用
    • 常量左值引用
  • 右值引用
  • 总结

在C++中,函数参数主要有两种方式:值类型和引用类型。其中引用类型又分为:左值引用和C++11引入的右值引用。下面我们分别对其进行介绍。

基本定义

要弄清楚这些概念,我们先要知道什么是左值,什么是右值。

  • 左值是指在内存中有确定存储地址的对象,可以在表达式中出现在赋值操作符的左侧。
  • 右值是指在表达式中没有持久存储地址的临时对象,通常出现在赋值操作符的右侧。

比如下面的代码中,a是左值,10是右值。

int a = 10;

值类型

值类型是最基本的参数类型。

在函数被调用时:

  • 如果实参是左值,它就会被复制一份到形参中(调用复制构造函数)。这意味着在函数体内对形参的任何修改都不会影响到实参本身。值传递适用于基本数据类型(如int, float等)和对象的小型拷贝开销可以接受的情况。
  • 如果实参是右值引用,则右值引用的对象会触发形参的移动构造函数。这减少了不必要的资源分配和释放,提高了性能。

我们设计了一个Custom类,它会在各个构造函数中打印this指针的值和相关标记信息,用于辅助我们查看和分析后续研究代码。

class Custom {
public:Custom(int value) : value(value) {std::cout << "Constructor Custom(" << value << "). this = " << this << std::endl;}Custom(const Custom& custom) : value(custom.value) {std::cout << "Copy constructor Custom(" << custom.value << "). this = " << this << " from " << &custom << std::endl;}Custom& operator=(const Custom& custom) {value = custom.value;std::cout << "Copy assignment operator Custom(" << custom.value << "). this = " << this << " from " << &custom << std::endl;return *this;}Custom(Custom&& custom) : value(custom.value) {std::cout << "Move constructor Custom(" << custom.value << "). this = " << this << " from " << &custom << std::endl;custom.value = 0;}Custom& operator=(Custom&& custom) {value = custom.value;std::cout << "Move assignment operator Custom(" << custom.value << "). this = " << this << " from " << &custom << std::endl;return *this;}~Custom() {std::cout << "Destructor Custom(" << value << "). this = " << this << std::endl;}friend std::ostream& operator<<(std::ostream& os, const Custom& custom) {os << custom.value;return os;}public:int get_value() const {return value;}void set_value(int value) {this->value = value;}private:int value;
};

下面的函数func的参数是值类型。

void func(Custom custom) {std::cout << "func(Custom custom) custom = " << custom << " from " << &custom << std::endl;
}

然后分别给func传入左值和右值,观察其执行过程。

int main(int argc, char* argv[]) {Custom custom(1);std::cout << "build custom in main" << std::endl;std::cout << "call func(custom)" << std::endl;func(custom);std::cout << "call func(std::move(custom))" << std::endl;func(std::move(custom));std::cout << "main end" << std::endl;return 0;
}

可以看到给值类型传入左值,会触发拷贝构造函数(过程2);给值类型传入右值引用,会触发移动构造函数(过程3)。
在这里插入图片描述

左值引用

左值引用(Lvalue Reference)是C++中的一种引用类型,用于引用一个左值(Lvalue)。左值引用的语法是使用单个 & 符号。

非常量左值引用

如果函数的参数是左值引用,这意味着函数直接操作的是原变量的内存地址,因此对形参的修改会反映到实参上。使用左值引用可以避免大型对象或结构体的复制开销,提高效率。

void func(Custom& custom) {std::cout << "func(Custom custom) custom = " << custom << " from " << &custom << std::endl;
}int main(int argc, char* argv[]) {Custom custom(1);Custom& custom2 = custom;const Custom& custom3 = custom;func(custom);func(custom2);// func(custom3);  // error// func(std::move(custom)); // error: cannot bind non-const lvalue reference of type 'Custom&' to an rvalue of type 'Custom'std::cout << "main custom = " << custom << " from " << &custom << std::endl;return 0;
}

需要注意的是:非常量左值引用(T&)只能绑定到左值,不能绑定到右值。

常量左值引用

有些时候,我们仅仅希望避免复制操作,而不希望函数修改原变量的值,这样我们就需要使用常量左值引用。

void func_const(const Custom& custom) {std::cout << "func_const(const Custom& custom) custom = " << custom << " from " << &custom << std::endl;
}int main(int argc, char* argv[]) {Custom custom(1);Custom& custom2 = custom;const Custom& custom3 = custom;func_const(custom);func_const(custom2);func_const(custom3);func_const(std::move(custom));  // const lvalue reference can bind to rvaluestd::cout << "main custom = " << custom << " from " << &custom << std::endl;return 0;
}

我们给常量左值引用形参传递值、左值引用、常量左值引用、右值引用都是可以的,其执行效果是一样的。

在这里插入图片描述

需要注意的是,传递右值引用并不出触发Custom的移动构造函数执行。我们不要被std::move这个函数名给骗了,它不会进行任何的“移动”操作。它只是将一个左值/右值强制转换成右值。

    constexpr typename std::remove_reference<_Tp>::type&&move(_Tp&& __t) noexcept{ return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }

右值引用

右值引用(Rvalue Reference)是C++11引入的一种引用类型,用于引用一个右值(Rvalue)。右值引用的语法是使用双 && 符号。

右值引用通常与移动语义结合使用,用于优化资源的转移,如动态分配的内存、文件句柄等。通过右值引用传递,我们可以避免在函数调用中不必要的资源复制,而是直接“移动”资源给函数内的变量。

void func(Custom&& custom) {std::cout << "func(Custom custom) custom = " << custom << " from " << &custom << std::endl;
}void func_const(const Custom&& custom) {std::cout << "func(Custom custom) custom = " << custom << " from " << &custom << std::endl;
}int main(int argc, char* argv[]) {Custom custom(1);Custom& custom2 = custom;const Custom& custom3 = custom;// func(custom); // error: cannot bind rvalue reference of type 'Custom&&' to lvalue of type 'Custom'// func(custom2); // error// func(custom3); // errorfunc(std::move(custom));// func_const(custom); // error: cannot bind rvalue reference of type 'const Custom&&' to lvalue of type 'Custom'// func_const(custom2); // error// func_const(custom3); // errorfunc_const(std::move(custom));std::cout << "main end" << std::endl;return 0;
}

右值引用形参只能接受右值引用实参。

总结

  • 当右值引用需要做复制操作时,会触发移动构造函数。
  • 值类型形参会触发复制操作,而引用类型不会触发复制操作。所以如果希望触发移动构造函数,需要将参数形参设计为值类型。

这篇关于Modern C++——函数参数类型的分类和使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1114233

相关文章

C++中全局变量和局部变量的区别

《C++中全局变量和局部变量的区别》本文主要介绍了C++中全局变量和局部变量的区别,全局变量和局部变量在作用域和生命周期上有显著的区别,下面就来介绍一下,感兴趣的可以了解一下... 目录一、全局变量定义生命周期存储位置代码示例输出二、局部变量定义生命周期存储位置代码示例输出三、全局变量和局部变量的区别作用域

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件