October 11, 20241 yr 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â¬Ã¡andâ¬Ã¡std::cref? The helper functions that generate objects of typeâ¬Ã¡std::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 ofâ¬Ã¡std::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 emulatesâ¬Ã¡T&â¬Ã¡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? View the full article
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.