Just Software Solutions

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: , , ,
Stumble It! stumbleupon logo | Submit to Reddit reddit logo | Submit to DZone dzone logo

Comment on this post

If you liked this post, why not subscribe to the RSS feed RSS feed or Follow me on Twitter? You can also subscribe to this blog by email using the form on the left.

20 Comments

Very informative blog. I like your blog because of unique content. thanks for sharing such a useful information.

by PHP Frameworks at 15:00:33 on Monday, 21 January 2019

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.
by Joe at 15:00:33 on Monday, 21 January 2019

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>
by online-dissertation-help at 15:00:33 on Monday, 21 January 2019

Very well explained tutorial.

by thomasgalvin at 15:00:33 on Monday, 21 January 2019
Nice article. Keep Sharing.
by John Blake at 15:00:33 on Monday, 21 January 2019

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>

by Head Racquets at 15:00:33 on Monday, 21 January 2019

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.

by MBT shoes at 15:00:33 on Monday, 21 January 2019

Great post..Thank you for the information you have shared..it is useful and helpful..Good job!

by Martin Broud at 15:00:33 on Monday, 21 January 2019

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>

by Dissertation India at 15:00:33 on Monday, 21 January 2019

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 !

by christian louboutin boots at 15:00:33 on Monday, 21 January 2019

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>

by dissertation proposal at 15:00:33 on Monday, 21 January 2019
<a href="http://www.amandamall.com/shoes-accessories_c11">Shoes Categories</a> <a href="http://www.amandamall.com/sports-shoes_c727">Sports Shoes</a> <a href="http://www.amandamall.com/dress-shoes_c729">Dress Shoes</a> <a href="http://www.amandamall.com/baby-shoes_c731">Baby Shoes</a> <a href="http://www.amandamall.com/slippers_c733">Slippers</a> <a href="ttp://www.amandamall.com/sandals_c735">Sandals</a> <a href="http://www.amandamall.com/clogs_c737">Clogs</a> <a href="http://www.amandamall.com/dance-shoes_c739">Dance Shoes</a> <a href="http://www.amandamall.com/special-purpose-shoes_c741">Special Purpose Shoes</a> <a href="http://www.amandamall.com/shoe-parts-accessories_c743">Shoe Parts & Accessories</a> <a href="http://www.amandamall.com/casual-shoes_c745">Casual Shoes</a> <a href="http://www.amandamall.com/sports-entertainment_c12">Sports & Entertainment</a> <a href="http://www.amandamall.com/outdoor-sports_c726">Outdoor Sports</a> <a href="http://www.amandamall.com/golf_c728">Golf</a> <a href="http://www.amandamall.com/indoor-sports_c730">Indoor Sports</a> <a href="http://www.amandamall.com/tennis_c732">Tennis</a> <a href="http://www.amandamall.com/sport-jesseys_c734">Sport Jesseys</a> very good posting. I liked it. thanks
by Free Shipping at 15:00:33 on Monday, 21 January 2019

<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>

by Tory Burch Shoes Sale at 15:00:33 on Monday, 21 January 2019

[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]

by christian louboutin boots sale at 15:00:33 on Monday, 21 January 2019

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>

by Dissertation Help at 15:00:33 on Monday, 21 January 2019

"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.

by Oakley Sunglasses at 15:00:33 on Monday, 21 January 2019

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'.

by Replica Rolex Watches at 15:00:33 on Monday, 21 January 2019

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.

by Cheap Birkenstock Shoes at 15:00:33 on Monday, 21 January 2019

Si on la n&eacute;glige trop, la facult&eacute; de cerner ses int&eacute;r&ecirc;ts et ses besoins a tendance &agrave; s&#8217;atrophier. C&#8217;est ce qui arrive quand on n&eacute;glige longtemps ses besoins en laissant aux autres le soin de d&eacute;cider ou en faisant passer leurs besoins avant les n&ocirc;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>

by mba dissertations uk at 15:00:33 on Monday, 21 January 2019

Cette r&eacute;alit&eacute; indispose un nombre toujours plus grand d'&ecirc;tres parlants, gyn&eacute;s ou gynandres, qui ne peuvent se r&eacute;signer &agrave; n'&ecirc;tre pas cause et effet de leur savoir-voir, de leur pens&eacute;e, de leur libido, de leur langue, et qui d&eacute;sirent un droit de pr&eacute;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>

by chanakya research dissertation at 15:00:33 on Monday, 21 January 2019

Add your comment

Your name:

Email address:

Your comment:

Design and Content Copyright © 2005-2024 Just Software Solutions Ltd. All rights reserved. | Privacy Policy