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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With