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++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五