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

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

C#如何调用C++库

《C#如何调用C++库》:本文主要介绍C#如何调用C++库方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录方法一:使用P/Invoke1. 导出C++函数2. 定义P/Invoke签名3. 调用C++函数方法二:使用C++/CLI作为桥接1. 创建C++/CL

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1