简体   繁体   English

分配运算符重载和自我分配

[英]Assignment Operator Overloading and Self Assignment

I've tried to understand Why in '=' overloading I have to check for self Assignment .I think i know the answer , it's because endless loop but I can't understand why the loop is started ?. 我试图理解为什么在'='重载中我必须检查自我赋值。我想我知道答案,这是因为循环不断,但我不明白为什么循环开始了。

Example : 范例:

Point p1(3,5);
p1 = p1 ;

It's not about endless recursion, at least not usually. 这与无休止的递归无关,至少通常不是这样。 The frequent issue with self-assignment is when you try to destroy a resource you own before copying the other object's one: if this object is actually the same, the resource is lost. 自我分配的常见问题是,当您尝试在复制另一个对象的资源之前销毁自己拥有的资源时:如果该对象实际上是相同的,则该资源将丢失。

struct Object {
    std::unique_ptr<Resource> _resource;

    Object &operator = (Object const &other) {
        _resource = nullptr;                // Destroy "my" resource
        _resource = clone(other._resource); // Nothing to clone anymore...
    }
};

The example is contrived: no one would first reset a pointer, then assign it. 该示例是人为设计的:没有人会先重置一个指针, 然后再分配它。 But this pattern popped up a lot in older C++, and is the origin of the "beware of self-assignment" advice. 但是这种模式在较早的C ++中突然出现,并且是“当心自我分配”建议的起源。

There is no loop. 没有循环。 What can happen is when you have a resource like some allocated memory. 当您拥有一些分配的内存之类的资源时,可能会发生什么。

If you have a shared pointer on some data. 如果您在某些数据上具有共享指针。 During the assignment, the first thing you do is de allocate your local data. 在分配过程中,您要做的第一件事是取消分配本地数据。 Then you replace it with the data from the other object. 然后,将其替换为来自另一个对象的数据。 If they are the same, then you lost your resource. 如果它们相同,那么您将失去资源。

The solution is then to check self assignments. 解决方案是检查自我分配。

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

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