问题描述
假设我有一个对象Employee_Storage
,其中包含数据库连接数据成员.该数据成员应该存储为指针还是引用?
Let's say I have an object Employee_Storage
that contains a database connection data member. Should this data member be stored as a pointer or as a reference?
-
如果我将其存储为参考,我 不必做任何
NULL
检查. (无论如何,NULL检查到底有多重要?)
If I store it as a reference, I don't have to do any
NULL
checking. (Just how important is NULL checking anyway?)
如果我将其存储为指针,则为 易于设置Employee_Storage
(或MockEmployee_Storage
) 测试的目的.
If I store it as a pointer, it's easier to setup Employee_Storage
(or MockEmployee_Storage
) for the purposes of testing.
通常,我一直习惯总是将数据成员存储为引用.但是,这使我的模拟对象难以设置,因为我现在必须传递true/mock对象,而不是能够传递NULL
s(大概是在默认构造函数中).
Generally, I've been in the habit of always storing my data members as references. However, this makes my mock objects difficult to set up, because instead of being able to pass in NULL
s (presumably inside a default constructor) I now must pass in true/mock objects.
是否有良好的经验法则,尤其是针对可测试性?
Is there a good rule of thumb to follow, specifically with an eye towards testability?
推荐答案
仅当引用是在构造时分配的,最好将引用存储为数据成员,并且确实没有理由更改它们.由于无法重新分配引用,因此引用非常有限.
It's only preferable to store references as data members if they're being assigned at construction, and there is truly no reason to ever change them. Since references cannot be reassigned, they are very limited.
通常,我通常将其存储为指针(或某种形式的模板化智能指针).这要灵活得多-既可以进行测试(如您所述),也可以按照常规用法使用.
In general, I typically store as pointers (or some form of templated smart pointer). This is much more flexible - both for testing (as you mentioned) but also just in terms of normal usage.
这篇关于什么时候最好将数据成员存储为引用而不是指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!