[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

reference_wrapper rationale

Felipe Farinon

11/11/2008 12:53:00 PM

1) I was wordering why the reference_wrapper’s [1] constructor is
explicit. For me it seens to be more useful wihout it. I want to
create a “view” of STL containers and the reference_wrapper class is
not so useful in this context.
For example,

int data[] = { 3, 7, 4 };
std::vector<std::tr1::reference_wrapper<int> > v;

for (int i = 0; i < 3; ++i)
v.push_back(ref(data[i]));

While without the explicit constructor we could do this way:

int data[] = { 3, 7, 4 };
std::vector<std::tr1::reference_wrapper<int> > v(&data[0], data + 3);

And besides that, the reference object makes more sense to be used as
in:

std::tr1::reference_wrapper<T> ref = my_variable;

2) Another usefull feature in the reference_wrapper would be to have:

std::tr1::reference_wrapper<T> operator=(const T& val)
{
*t_ = val;
return *this;
}

For cases when a person holds a container of reference_wrapper and
wants to modify any element:

int data[] = { 3, 7, 4 };
std::vector<std::tr1::reference_wrapper<int> > v(&data[0], data +
3);

std::replace(v.begin(), v.end(), 7, 30);

[1] http://msdn.microsoft.com/en-us/library/bb9....

1 Answer

Maxim Yegorushkin

11/12/2008 11:00:00 AM

0

On Nov 11, 12:53 pm, Felipe Farinon <Felipe.Fari...@gmail.com> wrote:
> 1) I was wordering why the reference_wrapper’s [1] constructor is
> explicit. For me it seens to be more useful wihout it.

I could not find an explanation, my only speculation is that it is
made explicit so as to protect from inadvertently creating long-lived
references to short-lived data, i.e. dangling references.

--
Max