简体   繁体   English

我可以为非const参考参数赋值吗?

[英]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 ? 在以下(遗留)代码块中,popped_value的赋值是有效还是应该有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; 在全局变量或局部变量的情况下, 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; 在任何其他时间,当您为该引用赋值时,您不会更改引用变量引用的内容,例如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. 如果value_type是自定义类,则将调用一些value_type operator=(...) Presumably the implementation of this method is sane. 据推测,这种方法的实施是理智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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