Scott Meyers的有效C++在第5章第28项中告诉我们避免将"句柄"(指针,引用或迭代器)返回到对象内部,这绝对是一个好点.
即不要这样做:
class Family
{
public:
Mother& GetMother() const;
}
Run Code Online (Sandbox Code Playgroud)
因为它破坏了封装并允许改变私有对象成员.
甚至不这样做:
class Family
{
public:
const Mother& GetMother() const;
}
Run Code Online (Sandbox Code Playgroud)
因为它可以导致"悬空手柄",这意味着您保留对已经销毁的对象的成员的引用.
现在,我的问题是,有什么好的选择吗?想象一下妈妈很沉重!如果我现在返回母亲的副本而不是参考,GetMother正在成为一个相当昂贵的操作.
你如何处理这种情况?
我正在编写一个近似函数,它将两个不同的公差值作为参数:
bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance)
Run Code Online (Sandbox Code Playgroud)
如果未设置verticalTolerance,我希望函数设置verticalTolerance = horizontalTolerance.所以,我想完成以下事情:
bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance=horizontalTolerance)
Run Code Online (Sandbox Code Playgroud)
我知道这是不可能的,因为不允许局部变量作为默认参数.所以我的问题是,设计这个功能的最佳方法是什么?
我想到的选项是:
不要使用默认参数并使用户明确设置两个容差.
将verticalTolerance的默认值设置为负值,如果为负,则将其重置为horizontalTolerance:
bool Approximate(vector<PointC*>* pOutput, LineC input, double horizontalTolerance, double verticalTolerance=-1)
{
if (verticalTolerance < 0)
{
verticalTolerance = horizontalTolerance;
}
// Rest of function
}
Run Code Online (Sandbox Code Playgroud)在我看来,第一点不是解决方案而是旁路,第二点不是最简单的解决方案.