对象的自赋值有什么用 [英] Is there any use with self assignment of object

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

问题描述

我知道使用对象的自赋值不是一个好主意,显然没有人明确地进行过这样的自赋值.

I know using self assignment of objects is not a good idea and obviously no one ever explicitly does a self assignment like this.

MyClass obj;
obj = obj;

C++ 是否有任何理由支持此功能或是否有任何特殊情况可以使用此功能?

Is there any reason why C++ supports this or is there any particular situation to use this?

推荐答案

除了 Carl Norum 和 Ralph Tandetzky 已经发布的答案之外,请问问自己编译器是否可以检测所有可能的自赋值.

In addition to the answers already posted by Carl Norum and Ralph Tandetzky ask yourself whether a compiler can detect all possible self-assignments.

答案应该是显而易见的,不,它不能.考虑一下这个相当简单(而且愚蠢)的代码片段:

The answer should be obvious, that no, it cannot. Consider this rather simple (and silly) snippet of code:

   Class obj1;
   Class obj2;

   Class *ptr = &obj1;

   if((rand() % 7) == 0)
       ptr = &obj2;

   obj2 = *ptr;

此代码有时会导致自赋值.编译器应该警告你吗?什么?海森堡错误 #3:rand() 返回 7 的倍数时的自赋值?"如果您的 rand 只返回范围 [0, 6]?

This code will sometimes result in self-assignment. Should the compiler warn you? With what? "Heisenberg Error #3: Self-assignment when rand() returns a multiple of 7?" What if your rand only returns numbers in the range [0, 6]?

这是一个简单的例子,编译器可以很容易地弄清楚.有更多复杂的代码片段更难捕获,但如果编译器对代码执行广泛流分析,则可以捕获,但运行时间会更长.而且,当然,有非常复杂的代码片段可以表现出这种行为,但很难甚至不可能捕捉到.

And this is a simple example that a compiler could fairly easily figure out. There are more convoluted snippets of code that would be a lot more difficult to catch, but could be caught if the compiler performed extensive flow analysis of the code but then it would take much longer to run. And, of course, there are very convoluted snippets of code that can exhibit this behavior that are very hard or even impossible to catch.

因此,您的编译器可能需要更长的时间才能运行,但有时会以概率警告您潜在的自赋值.坦率地说,这比没有警告更糟糕.

So, you could have a compiler that took much longer to run only to sometimes probabilistically warn you about a potential self-assignment. Frankly, that's worse than not warning.

如果您觉得这是一个问题并且您不想允许它,那么拥有一个写着禁止自我分配!"的编码标准.可能是更好的主意.

If you feel that this is a problem and you don't want to allow it, then having a coding standard that says "no self-assignments!" is probably the better idea.

旁注:有一些工具可以进行大量非常复杂的源代码分析,以尝试找出问题的根源;此类工具可以配置为并将捕获许多此类自赋值,包括一些复杂的赋值.但它们仍然无法捕获所有内容,需要一段时间才能运行,而且通常要花费数千美元.

Sidenote: There are tools that can do a lot of very sophisticated source code analysis to try and root out issues; such tools can be configured to and will catch many such self-assignments, including some convoluted ones. But they still don't catch everything, take a while to run and typically cost in the thousands of dollars.

这篇关于对象的自赋值有什么用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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