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?

asked Nov 24, 2016 at 15:33

Cem Kalyoncu's user avatar

2

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

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

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

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.

answered Nov 24, 2016 at 15:33

Cem Kalyoncu's user avatar

6 Comments

Now I can detect problems with passing temporaries at compile-time. Thanks a lot!

2019-03-23T19:34:33.8Z+00:00

I would really appreciate if you could elaborate more on how std::reference_wrapper works in this case. What happens if the arguments is a temporary obj std::string, and the function returns a pointer to its .data()? Will it work in this case?

2020-04-21T08:30:57.963Z+00:00

I think (not sure) 3rd option uses a constructor with r-value overload deleted. Thus it will prevent temporary to be passed as a reference.

2020-04-22T09:17:06.743Z+00:00

Note that option 1 requires linearly (or exponential, if you want to avoid ambiguity) many overloads if you have multiple const reference arguments which you need prevent temporaries from being passed.

2020-06-17T18:26:22.793Z+00:00

What is meant by the third method being "too explicit"?

2021-02-25T19:05:32.64Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.