赋值运算符改变赋值对象的值 [英] Assignement operator changing value of the assigned object

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

问题描述

我实现了一个类来处理一些外部函数(例如另一个 DLL).这个函数给了我一个可以用作句柄的整数.这是我的代码的重要部分:

I implemented a class to handle some external functions (e.g of another DLL). This functions gives me an integer I can use as a handle. Here is the important part of my code:

MyClass
{
public:
    MyClass() { 
        handle = getHandlefromExternalFunction();
    }
    ~MyClass {
        if(handle>0)
            freeHandleFromExternalFunction(handle);
    }
    MyClass& operator=(MyClass& other) {
        freeHandleFromExternalFunction(handle);
        handle = other.handle
        other.handle = 0; //Is this a bad idea?
    }
private:
    int handle;
}

在我的主函数中,我有一个 myClass 对象.在某些时候,我使用赋值运算符来更改对象的值:

In my main function I have an object of myClass. At some point I am using the assignement operator to change the values of the object:

MyClass object;
//some code
object = MyClass();

赋值后由 MyClass() 创建的对象会立即销毁,因为它超出了范围.但我不希望 freeHandleFromExternalFunction() 在那个 handle 上被调用,因为我在分配的对象中使用它.因此,我在赋值运算符 handle = 0 中更改了分配对象的值.我的问题是:这是一个坏主意吗?有人对我的问题有更好的解决方案吗?

After assignement the object created by MyClass() is immediatly destroyed since it gets out of scope. But I don't want freeHandleFromExternalFunction() to be called on that handle, since I am using it in the assigned object. Therefor I change the value of the assigned object in the assignement operator handle = 0. My question is: Is this a bad idea? Has anybody a better solution for my problem?

推荐答案

是的,这是个坏主意.您通常不希望修改作业的右侧.

Yes it's a bad idea. You don't normally expect the right-hand side of an assignment to be modified.

如果您想移动所有权,则将移动"赋值运算符与 std::move:

If you want to move ownership then use the "move" assignment operator together with std::move:

MyClass& operator=(MyClass&& other) { ... }

// ...

MyClass a = ...;
MyClass b;

b = std::move(a);

如果您想要这样的移动(其中只能是所包含资源的一个所有者),那么我还建议您将复制构造函数和复制赋值运算符标记为已删除:

If you only want movement like this (where the can be only one owner of the contained resource), then I also suggest you mark the copy-constructor and copy-assignment operators as deleted:

MyClass& operator=(MyClass const&) = delete;
MyClass(MyClass const&) = delete;

遵循五的规则不要忘记移动构造函数和析构函数:

And following the rule of five don't forget the move-constructor and destructor:

~MyClass() { ... }
MyClass(MyClass&& other) { ... }

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

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