Title
reference_wrapper, cref unsafe, allow binding to rvalues
Status
c++11
Section
[refwrap.const]
Submitter
Peter Dimov

Created on 2007-05-10.00:00:00 last changed 161 months ago

Messages

Date: 2010-10-21.18:28:33

Proposed resolution:

In [function.objects], add the following two signatures to the synopsis:

template <class T> void ref(const T&& t) = delete;
template <class T> void cref(const T&& t) = delete;
Date: 2010-10-21.18:28:33

[ Batavia (2009-05): ]

We agree with the proposed resolution. Move to Tentatively Ready.

Date: 2009-05-10.00:00:00

[ 2009-05-10 Howard adds: ]

Without:

template <class T> void ref(const T&& t) = delete;

I believe this program will compile:

#include <functional>

struct A {};

const A source() {return A();}

int main()
{
   std::reference_wrapper<const A> r = std::ref(source());
}

I.e. in:

template <ObjectType T> reference_wrapper<T> ref(T& t);

this:

ref(source())

deduces T as const A, and so:

ref(const A& t)

will bind to a temporary (tested with a pre-concepts rvalue-ref enabled compiler).

Therefore I think we still need the ref-protection. I respectfully disagree with Alisdair's comment and am in favor of the proposed wording as it stands. Also, CWG 606 (noted below) has now been "favorably" resolved.

Date: 2009-05-09.00:00:00

[ 2009-05-09 Alisdair adds: ]

Now that ref/cref are constained that T must be an ObjectType, I do not believe there is any risk of binding ref to a temporary (which would rely on deducing T to be an rvalue reference type)

However, the problem for cref remains, so I recommend retaining that deleted overload.

Date: 2007-05-10.00:00:00

A reference_wrapper can be constructed from an rvalue, either by using the constructor, or via cref (and ref in some corner cases). This leads to a dangling reference being stored into the reference_wrapper object. Now that we have a mechanism to detect an rvalue, we can fix them to disallow this source of undefined behavior.

Also please see the thread starting at c++std-lib-17398 for some good discussion on this subject.

History
Date User Action Args
2011-08-23 20:07:26adminsetstatus: wp -> c++11
2010-10-21 18:28:33adminsetmessages: + msg3447
2010-10-21 18:28:33adminsetmessages: + msg3446
2010-10-21 18:28:33adminsetmessages: + msg3445
2010-10-21 18:28:33adminsetmessages: + msg3444
2007-05-10 00:00:00admincreate