reference_wrapper rationale

F

Felipe Farinon

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

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/bb982605.aspx.
 
M

Maxim Yegorushkin

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top