Reference Wrappers Explained
Wednesday, 14 July 2010
The
upcoming C++0x
standard includes reference wrappers in the form of
the std::reference_wrapper<T>
class template, and
the helper function templates std::ref()
and std::cref()
. As I mentioned in my blog post
on Starting
Threads with Member Functions and Reference Arguments, these
wrappers can be used to pass references to objects across interfaces
that normally require copyable (or at least movable) objects
— in that blog post, std::ref
was used for passing
references to objects over to the new thread, rather than copying the
objects. I was recently asked what the difference was
between std::ref
and std::cref
, and how they
worked, so I thought I'd elaborate.
Deducing the Referenced Type
std::ref
is a function template, so automatically
deduces the type of the wrapped reference from the type of the
supplied argument. This type deduction includes
the const
-ness of the supplied object:
int x=3; const int y=4; std::reference_wrapper<int> rx=std::ref(x); // std::reference_wrapper<int> ry=std::ref(y); // error std::reference_wrapper<const int> rcy=std::ref(y);
On the other hand, though std::cref
also deduces the
type of the wrapped reference from the supplied argument,
it always wraps a const
reference:
int x=3; const int y=4; // std::reference_wrapper<int> rx=std::cref(x); // error std::reference_wrapper<const int> rcx=std::cref(x); // std::reference_wrapper<int> ry=std::cref(y); // error std::reference_wrapper<const int> rcy=std::cref(y);
Since a no-const
-reference can always be bound to
a const
reference, you can thus
use std::ref
in pretty much every case where you would
use std::cref
, and your code would work the same. Which
begs the question: why would you ever choose to
use std::cref
?
Using std::cref
to prevent modification
The primary reason for choosing std::cref
is because
you want to guarantee that the source object is not modified through
that reference. This can be important when writing multithreaded
code — if a thread should not be modifying some data then it
can be worth enforcing this by passing a const
reference rather than a mutable reference.
void foo(int&); // mutable reference int x=42; // Should not be modified by thread std::thread t(foo,std::cref(x)); // will fail to compile
This can be important where there are overloads of a function such
that one takes a const
reference, and the other a
non-const
reference: if we don't want the object
modified then it is important that the overload taking
a const
reference is chosen.
struct Foo { void operator()(int&) const; void operator()(int const&) const; }; int x=42; std::thread(Foo(),std::cref(x)); // force const int& overload
References to temporaries
std::cref
has another property missing
from std::ref
— it can bind to temporaries, since
temporary objects can bind to const
references. I'm
not sure this is a good thing, especially when dealing with multiple
threads, as the referenced temporary is likely to have been
destroyed before the thread has even started. This is therefore
something to watch out for:
void bar(int const&); std::thread t(bar,std::cref(42)); // oops, ref to temporary
Documentation
Finally, std::cref
serves a documentation purpose,
even where std::ref
would suffice — it declares
in big bold letters that this reference cannot be used to modify the
referenced object, which thus makes it easier to reason about the
code.
Recommendation
I would recommend that you use std::cref
in preference
to std::ref
whenever you can — the benefits as
documentation of intent, and avoiding accidental modification
through the reference make it a clear winner in my opinion. Of
course, if you do want to modify the referenced
object, then you need to use std::ref
, but such usage
now stands out, and makes it clear that this is the intent.
You do still need to be careful to ensure that you don't try and
wrap references to temporaries, particularly when
applying std::cref
to the result of a function call,
but such uses should stand out — I expect most uses to be
wrapping a reference to a named variable rather than wrapping a
function result.
Posted by Anthony Williams
[/ cplusplus /] permanent link
Tags: reference wrappers, ref, cref, cplusplus
Stumble It! | Submit to Reddit | Submit to DZone
If you liked this post, why not subscribe to the RSS feed or Follow me on Twitter? You can also subscribe to this blog by email using the form on the left.
Design and Content Copyright © 2005-2024 Just Software Solutions Ltd. All rights reserved. | Privacy Policy
20 Comments
Very informative blog. I like your blog because of unique content. thanks for sharing such a useful information.
You might be interested to learn that the latest C++0x draft contains deleted versions of both ref and cref:
template <class T> void ref(const T&& t) = delete; template <class T> void cref(const T&& t) = delete;
This prevents ref and cref from binding to temporaries.This post includes all information that I have always required. Although on internet we find a lot of information but the practical information is limited which you have originated in this post.
<a href="http://www.online-dissertation-help.com/dissertation_proposal.htm">Dissertation proposal</a>Very well explained tutorial.
Htc bravo, this concept is needed just by how
<a href="http://www.tennisracquetsshops.com/babolat-pure-drive-gt-plus-tennis-racquets-p-44.html" title="wilson ncode ntour two 95 tennis racquets brand new">wilson ncode ntour two 95 tennis racquets brand new</a> |<a href="http://www.tennisracquetsshops.com/babolat-tennis-racquets-c-2.html" title="wilson ncode rackets n5">wilson ncode rackets n5</a> |<a href="http://www.tennisracquetsshops.com/head-tennis-racquets-c-3.html" title="wilson ncode racquets">wilson ncode racquets</a>
MBT shoes are scientifically proven to produce health benefits for your muscles, joints, and internal systems. http://www.mbtshoessalecheap.net MBT soles are curved instead of flat. MBT footwear is naturally unstable, not rigid and supportive; they work your muscles to make them healthier instead of undermining them to wear them out. http://www.mbtshoessalecheap.net MBT shoes are designed to help your entire body, not just your feet.
Great post..Thank you for the information you have shared..it is useful and helpful..Good job!
In the 4th point ..i know that The compiler cannot deduce the value of a major array bound unless the bound refers to a reference or pointer type. Major array bounds are not part of function parameter types
<p><a href="http://dissertationhelp.9f.com/">dissertation india</a><br /></p>
Wedohavetheatest<a href=http://http://www.christianlouboutinbootss.com/christian-louboutin-pumps-c-12.html/>Christian Louboutin Pumps</a>,here you can get 80% prices off and free shipping. Top brand <a href=http://http://www.christianlouboutinbootss.com/christian-louboutin-boots-c-16.html/>Christian Louboutin Boots</a> with signature red sole is well-known by most fashionista. Because of the special and unique meticulous design, even many super stars can not ignore its existence. <a href=http://http://www.christianlouboutinbootss.com/christian-louboutin-peep-toe-c-13.html/>Christian Louboutin Peep Toe</a> so sexy and gorgeous are published on the kinds of magazines and newspapers, from razor-sharp stilettos to studded sneakers you always could find your favorite and love on our online<a href=http://http://www.christianlouboutinbootss.com/christian-louboutin-wedges-c-17.html/>Christian Louboutin Wedges</a> Welcome to our online store !
Taking creatine supplements may increase the amount of creatine in the muscles. Muscles may be able to generate more energy or generate energy at a faster rate. Some people think that taking creatine supplements along with training will improve performance by providing quick bursts of intense energy for activities such as sprinting and weightlifting.
<p><a href="http://dissertationhelp.9f.com/">dissertation proposal</a><br /></p>
<strong><a href="http://www.newtoryburchshoessale.com" title="Tory Burch Shoes" >Tory Burch Shoes</a></strong> <strong><a href="http://www.newtoryburchshoessale.com" title="Tory Burch Sale" >Tory Burch Sale</a></strong> <strong><a href="http://www.newtoryburchshoessale.com" title="Tory Burch Shoes Sale" >Tory Burch Shoes Sale</a></strong> <strong><a href="http://www.newtoryburchshoessale.com" title="Buy Tory Burch Shoes" >Buy Tory Burch Shoes</a></strong>
[url=http://www.christian-louboutin-boots.com/louboutin-peep-toe-booties-c-140.html]Christian Louboutin Shoes Discount Coupon[/url] [url=http://www.christian-louboutin-boots.com/louboutin-otk-boots-c-139.html]Christian Louboutin Studded Boots Sale[/url] [url=http://www.christian-louboutin-boots.com/louboutin-booties-c-138.html]Replica Christian Louboutin Shoes Men[/url] [url=http://www.christian-louboutin-boots.com/louboutin-boots-c-137.html]Christian Louboutin Outlet Store Reviews[/url]
No there is no simple way. The type name will be rather long and even more unreadable. And if you use boost, you don't need to use
<p><a href="http://dissertationhelp.4t.com">dissertation help</a><br /></p>
"The politics are not in our favor," he said, noting that Oakley is taking an unpopular stand in light of the pro-environment attitudes that dominate the Bay Area.
If you need a wristwatch that may be guaranteed to last eternally, practically, next Kama'aina ( company is without a doubt, what exactly you're in search of. Get rid of battery power you actually mans. No more having to worry regarding 'if ones check out will certainly last'or if 'it go away from a specific time' or maybe if 'it's waterproof'.
I wanted to thank you for this interesting I definitely loved every little bit of it. I have you bookmarked your web site to check out the latest stuff you post.
Si on la néglige trop, la faculté de cerner ses intérêts et ses besoins a tendance à s’atrophier. C’est ce qui arrive quand on néglige longtemps ses besoins en laissant aux autres le soin de décider ou en faisant passer leurs besoins avant les nôtres.
<a href="http://dissertationhelpindia.com/" rel="nofollow"> mba uk dissertations </a><br />
<a href="http://dissertationhelpindia.com/dissertation_writers_from_india.html" rel="nofollow"> dissertation help india </a><br />
<a href="http://dissertationhelpindia.com/uk_dissertations.html" rel="nofollow"> msc dissertations uk </a><br />
<a href="http://dissertationhelpindia.com/dissertation_india.html" rel="nofollow"> marketing dissertations </a><br />
<a href="http://dissertationhelpindia.com/uk_dissertations.html" rel="nofollow"> mba dissertations uk </a><br />
<a href="http://dissertationhelpindia.com/spss_dissertation_help.html" rel="nofollow"> mba thesis uk </a><br />
<a href="http://dissertationhelpindia.com/dissertation_india.html" rel="nofollow"> uk dissertations mba </a><br />
<a href="http://dissertationhelpindia.com/uk_dissertations.html" rel="nofollow"> uk dissertations msc </a><br />
<a href="http://dissertationhelpindia.com/dissertation_writers_from_india.html" rel="nofollow"> dissertation writers from india </a><br />
<a href="http://dissertationhelpindia.com/dissertation_topics.html" rel="nofollow"> research proposal uk </a><br />
<a href="http://dissertationhelpindia.com/contact_us.html" rel="nofollow"> mba dissertation uk </a><br />
<a href="http://dissertationhelpindia.com/dissertation_writers_from_india.html" rel="nofollow"> uk dissertations writers </a><br />
<a href="http://dissertationhelpindia.com/uk_dissertations.html" rel="nofollow"> mba thesis uk </a><br />
<a href="http://dissertationhelpindia.com/dissertation_samples.html" rel="nofollow"> msc thesis uk </a><br />
<a href="http://dissertationhelpindia.com/dissertation_writers_from_india.html" rel="nofollow"> phd thesis uk </a><br />
<a href="http://dissertationhelpindia.com/dissertation_topics.html" rel="nofollow"> msc dissertations uk </a>
Cette réalité indispose un nombre toujours plus grand d'êtres parlants, gynés ou gynandres, qui ne peuvent se résigner à n'être pas cause et effet de leur savoir-voir, de leur pensée, de leur libido, de leur langue, et qui désirent un droit de préemption sur leur avenir.
<p><a href="http://ukdissertationhelpindia.tumblr.com/ "rel="nofollow"> chanakya research </a><br />
<p><a href="http://ukdissertationhelpindia.tumblr.com "rel="nofollow"> chanakaya research </a><br />
<p><a href="http://ukdissertationhelpindia.tumblr.com "rel="nofollow"> chanakya research dissertation </a><br />
<p><a href="http://ukdissertationhelpindia.tumblr.com "rel="nofollow"> chanakya research dissertation india </a><br />
<p><a href="http://ukdissertationhelpindia.tumblr.com "rel="nofollow"> dissertation india </a><br />
<p><a href="http://ukdissertationhelpindia.tumblr.com "rel="nofollow"> dissertation help india </a><br />
<p><a href="http://ukdissertationhelpindia.tumblr.com "rel="nofollow"> elk india </a><br />
<p><a href="http://ukdissertationhelpindia.tumblr.com "rel="nofollow"> chanakyaresearchcom </a>