ARTICLE AD BOX
Asked 9 years, 3 months ago
Viewed 2k times
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?
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.
6 Comments
Explore related questions
See similar questions with these tags.


