reference_wrapper rationale

Discussion in 'C++' started by Felipe Farinon, Nov 11, 2008.

  1. 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.
     
    Felipe Farinon, Nov 11, 2008
    #1
    1. Advertising

  2. On Nov 11, 12:53 pm, Felipe Farinon <> 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
     
    Maxim Yegorushkin, Nov 12, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Harald Kirsch
    Replies:
    0
    Views:
    397
    Harald Kirsch
    Jun 14, 2004
  2. Alexander Grigoriev
    Replies:
    0
    Views:
    406
    Alexander Grigoriev
    Sep 12, 2003
  3. Asfand Yar Qazi
    Replies:
    5
    Views:
    375
    Siemel Naran
    Apr 7, 2004
  4. Christopher Benson-Manica

    gets() rationale

    Christopher Benson-Manica, Dec 2, 2003, in forum: C Programming
    Replies:
    52
    Views:
    1,472
    Mark McIntyre
    Dec 15, 2003
  5. Emmanuel Deloget
    Replies:
    2
    Views:
    487
    Emmanuel Deloget
    Nov 29, 2006
Loading...

Share This Page