By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,949 Members | 1,345 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,949 IT Pros & Developers. It's quick & easy.

reference_wrapper rationale

P: n/a
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<Tref = my_variable;

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

std::tr1::reference_wrapper<Toperator=(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.

Nov 11 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Nov 11, 12:53*pm, Felipe Farinon <Felipe.Fari...@gmail.comwrote:
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
Nov 12 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.