When working with C++ standard containers and functions, handling references can sometimes lead to unexpected behavior, particularly with copy semantics. This is where std::ref
and std::cref
come into play, allowing you to store references in containers and pass them safely to template functions like std::bind
or std::thread
.
What is std::ref?
by Sandor Dargo
From the article:
Have you heard about
std::ref
andstd::cref
? The helper functions that generate objects of typestd::reference_wrapper
? The answer is probably yes. In that case, this article is probably not for you. But if you haven’t heard about them, or the only usage ofstd::reference_wrapper
you faced was storing references in a vector, then probably it’s worth reading on.This article is inspired by some failing tests that needed me to use
std::ref
in order to pass them.What does
reference_wrapper
do?A reference of an object
T
(T&
) is not copy assignable. On the other hand,std::reference_wrapper<T>
which emulatesT&
it both copy-constructible and copy-assignable. It’s even trivially copyable, so copying can take place on a byte level which makes it very efficient.So when should we use such a wrapper?
Add a Comment
Comments are closed.