Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent passing temporary for const ref parameter

I have a function:

void AddImage(const Image &im);

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?

like image 859
Cem Kalyoncu Avatar asked Nov 24 '16 15:11

Cem Kalyoncu


1 Answers

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

  1. Delete the overload with r-value parameter: void AddImage(const Image &&) = delete;

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

  3. Use reference wrapper: void AddImage(std::reference_wrapper<const Image>)

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.

like image 135
Cem Kalyoncu Avatar answered Oct 10 '22 10:10

Cem Kalyoncu