简体   繁体   中英

Can I assign a value to a non-const reference parameter?

In the following (legacy) code block, is the assignment to popped_value valid or should there be a memcpy ?

bool peek(value_type& popped_value)
    {
    bool retval=false;
    RWLock::ScopedReadLock lock(queueLock);
    if ( ! m_queue.empty())
        {
        popped_value=m_queue.front(); //question...
        retval=true;
        }
    return retval;
    }

I don't want to change the parameter to a pointer.

The only place you can set the object that a reference variable references is when the reference variable is created:

  • In the case of a global or local variable, the Type & ref = value; statement that defines the variable,
  • In the case of a non-static data member of some class, the initialization list in a constructor for that class, or
  • In the case of an argument to some function that is a reference, in the statement that calls that function.

At any other time, you are not changing the thing that reference variable references when you assign a value to that reference, eg, reference_variable = value; . You are instead changing the value of the thing to which that reference variable refers.

That almost certainly is exactly the desired behavior in the referenced block of code.

That's fine, and it's how I would expect that to be written.

If value_type is a custom class, then some value_type operator=(...) will be called. Presumably the implementation of this method is sane.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM