具有const ref参数的自赋值行为 [英] Behavior of self-assignment with const ref parameter

查看:63
本文介绍了具有const ref参数的自赋值行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一些非常旧的代码,该代码具有一个带有已定义的副本分配运算符的类,该运算符将其参数用作const引用,但也不会检查自赋值,因此本质上是:

I stumbled upon some very old code which has a class with a defined copy assignment operator which takes its parameter as a const reference, but also does not check for self-assignment, so essentially:

struct A
{
    int q;
    A(): q(3) {}

    A& operator=(const A& a)
    {
        q = a.q;
        return *this;
    }
};

A 的实例分配给自身时,该赋值运算符的行为是什么?我认为这会导致问题,因为它破坏"了参数的稳定性,任何编译器都可以假设参数未更改,并以此为基础进行优化.

What is the behavior of this assignment operator when an instance of A is assigned to itself? I would assume this causes problems as it "breaks" the constness of the paramater, any compiler could assume that the parameter is not changed and optimize based on this.

但是clang和gcc都不会发出警告,并且程序可以正常运行.如果在赋值运算符中赋值之前将 q 的值显式更改为4,这也将起作用.

However neither clang nor gcc emit a warning, and the program runs fine. This also works if I explicitly change the value of q to 4 before the assignment in the assignment operator.

推荐答案

将对象绑定到const引用不会使它突然变成const.此处的 const 仅表示该函数无法通过 a 修改参数.这并不意味着所引用的对象必须是const本身.

Binding an object to a const reference doesn't make it const all of a sudden. The const there only indicates that the function cannot modify the parameter via a. It doesn't mean that the referred to object has to be const itself.

由于 * this a 可以合法地别名相同的对象,因此此类代码没有风险.编译器无法对别名做出疯狂的假设.

Since *this and a can legally alias the same object, there's no risk in such code. The compiler cannot make wild assumptions about aliasing.

自赋值仅是一个问题,如果赋值运算符没有运行到完成状态,或者释放了一个资源然后尝试从其他"中复制资源,则该对象状态可能因某种原因而被破坏了.您的示例没有发生这种情况的风险.但总的来说,应该牢记可能引发的异常和资源所有权.

Self-assignment is only an issue when the object state can be left somehow corrupted if the assignment operator doesn't run to completion, or releases a resource it then tries to copy from "other". Your example has no risk of that happening. In general however, one should be mindful of exceptions potentially being thrown and ownership of resources.

这篇关于具有const ref参数的自赋值行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆