分配运算符更改分配对象的值 [英] Assignement operator changing value of the assigned object

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

问题描述

我实现了一个类来处理一些外部函数(例如另一个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()创建的对象超出范围,因此会立即将其销毁.但是我不希望在该handle上调用freeHandleFromExternalFunction(),因为我在分配的对象中使用它.因此,我在赋值运算符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.

如果要移动所有权,则将"move"赋值运算符与 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天全站免登陆