防止为const ref参数临时传递 [英] Prevent passing temporary for const ref parameter

查看:46
本文介绍了防止为const ref参数临时传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数:

void AddImage(const Image &im);

此函数不需要更改图像,但它存储图像以使用const引用后来。因此,此功能不应允许临时使用。在没有任何预防措施的情况下,以下工作如下:

This function does not need image to be modifiable, but it stores the image a const reference to be used later. Thus, this function should not allow temporaries. Without any precaution the following works:

Image GetImage();

...

AddImage(GetImage());

是否可以防止此函数调用?

Is there a way to prevent this function call?

推荐答案

有两种机制可以防止将临时参数传递给const ref参数。

There are couple of mechanisms that prevent passing temporary to a const ref parameter.


  1. 使用r-value参数删除重载: void AddImage(const Image&) =删除;

使用const指针: void AddImage(const Image *)。此方法将在C ++ 11之前的版本中运行

Use const pointer: void AddImage(const Image*) . This method will work pre-C++11

使用引用包装器: void AddImage(std :: reference_wrapper< const Image>)

使用支持C ++ 11的编译器时,首选第一种方法。这使意图很明确。第二种方法要求对 nullptr 进行运行时检查,并且不能传达图像不能为空的想法。第三种方法行之有效,使意图很明确,但是,它太明确了。

First method should be preferred when using C++11 supporting compiler. It makes the intention clear. Second method requires a runtime check of nullptr and does not convey the idea that the image cannot be null. Third method works and makes the intention clear, however, it is too explicit.

这篇关于防止为const ref参数临时传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆