“重新初始化” /清理类实例的最短和最佳方法 [英] Shortest and best way to "reinitialize"/clean a class instance

查看:76
本文介绍了“重新初始化” /清理类实例的最短和最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将简短介绍一下,仅向您显示代码示例:

I will keep it short and just show you a code example:

class myClass
{
public:
  myClass();
  int a;
  int b;
  int c;
}

// In the myClass.cpp or whatever
myClass::myClass( )
{
 a = 0;
 b = 0;
 c = 0;
}

好的。如果我知道有一个myClass实例,并为a,b和c设置了一些随机垃圾。

Okay. If I know have an instance of myClass and set some random garbage to a, b and c.


  • 重置它们的最佳方法是什么在调用类构造函数后,状态全部变为0,那么:0、0和0?

我想出了这种方式:

myClass emptyInstance;
myUsedInstance = emptyInstance; // Ewww.. code smell?

或..

myUsedInstance.a = 0; myUsedInstance.c = 0; myUsedInstance.c = 0; 




  • 我想你知道我想要什么,有没有更好的方法

  • 推荐答案

    myUsedInstance = myClass();
    

    如果使用此格式,C ++ 11非常有效;移动分配操作员将负责手动清洁每个成员。

    C++11 is very efficient if you use this form; the move assignment operator will take care of manually cleaning each member.

    这篇关于“重新初始化” /清理类实例的最短和最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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