可以为无行为的聚合提供构造函数+平凡的运算符吗? [英] Ok to provide constructor + trivial operators for behaviorless aggregates?

查看:97
本文介绍了可以为无行为的聚合提供构造函数+平凡的运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对 2043381

请考虑以下内容:

struct DataBundle
{
   std::string name;
   int age;

   DataBundle() : age(0) {}
   DataBundle(const std::string& name, int age)
       : name(name), age(age) {}
   void swap(DataBundle& rhs)
       {name.swap(rhs.name); std::swap(age, rhs.age);}
   DataBundle& operator=(DataBundle rhs) {swap(rhs); return *this;}
   bool operator==(const DataBundle& rhs) const
       {return (name == rhs.name) && (age == rhs.age);}
   bool operator!=(const DataBundle& rhs) const {return !(*this == rhs);}
}

本着C ++编码标准第41条的精神(请参阅相关的文章),是否仍将其视为无行为的集合?我不喜欢用大量的getter / setter来编写笨拙的类,而宁愿使用一个全公开的结构来表示它只是一个 bundle-o-data。但是在上面的示例中,我是否应该使DataBundle成为具有getter / setter的类?

In the spirit of rule #41 of C++ Coding Standards (see related article), would this still be considered a behaviorless aggregate? I don't like writing "dumb" classes with mostly getters/setters, and would rather use an all-public struct to indicate it's just a "bundle-o-data". But in the above example, am I at the point where I should make DataBundle a class with getters/setters?

推荐答案

否,不需要吸气剂和二传手。它仍然是一个普通的数据结构,没有方法可以执行修改数据结构的操作-在这里比较,分配,交换都不是行为,这是语言执行基本操作和使数据结构实际可用所必需的。

No, no need for getters and setters yet. It is still a plain data structure where no methods implement actions modifying the data structure - compare, assign, swap are no 'behaviour' here, they're stub needed by the language to perform basic operations and to make the data structure actually usable.

您需要确定结构字段之间是否存在任何依赖项或不变量。如果它们存在(或将来可能存在),请使用getter或setter来确保它们(即,如果属性b发生更改,请调整属性a)。如果不是,则将所有内容声明为公共。 名称 age 是人类的分离属性,我认为这里不需要访问器。当然,这只是口味问题。

You need to decide whether there are any dependencies or invariants to be hold between the fields of structure. If they exist (or may exist in future), use getters or setters to ensure them (i.e. adjust attribute a if attribute b is changed). If not, declare everything public. name and age are decoupled properties of a human being, I don't think accessors are really necessary here. Of course it's a matter of taste.

这篇关于可以为无行为的聚合提供构造函数+平凡的运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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