2013-11-02 35 views
1

考虑下面这个简单的函数声明:返回的值 - 错误指示值

vector<Date> getMonthArray(int month, int year); 

至于C++ 11,我可以利用移动语义的和值,而不损失任何性能的返回日期矢量和避免使用'新'和'删除'。

问题是,如果功能失败,则不知道该返回什么。 E.G.一个月或一年都低于零

我都不能返回null,因为我可以用指针做, 所以我想到了两种可能性:

1)返回一个空数组 2)抛出一个异常

说实话,我讨厌这两个。很想听听更有经验的C++程序员的更好的解决方案。

编辑:

所以,抛出一个异常,真的看起来像最优雅的解决方案,因为它不涉及用户的需要,为了正常运行的功能(可抛出的异常,除了阅读任何文件)。我对么?或者其他更多的选择?

+0

在此处抛出异常是要走的路。 – rightfold

+0

@rightfold:护理阐述?在这种情况下,你怎么可能知道什么是OP的“正确”解决方案?异常处理可以是一个棘手的野兽,然后有各种各样的关于在哪里检查异常,这也正是他们应该处理的问题。也许对于有机磷农药代码的最好的事情就是打电话getMonthArray之前验证输入,因为他们可以,然后有依赖于该验证的输入等功能。我的观点是,不知道OP的代码库,称“使用例外”需要配备大量的盐。 – AndyG

回答

0

如果它可能失败,一个空向量不是一个可怕的想法。人们似乎喜欢返回错误代码的一种方法就是将该向量作为参考参数,并将函数的返回值更改为布尔值,或者如果返回代码类型更多,则返回int(可以是枚举类型,太)。根据返回的值,不同的条件可能适用于您的矢量。我认为在这种情况下,尽管一个空的向量可以很好地记录下来。参考参数,布尔返回方法的错误代码

//pre: none 
//post: if month and year are valid, monthArray will contain array 
//  of months and function returns true. 
//  Otherwise returns false with no guarantees on contents of monthArray 
bool getMonthArray(int month, int year, vector<Date>& monthArray); 

实施例中,参考参数

//pre: none 
//post: if month and year are valid, monthArray will contain array 
//  of months and function returns 0 for success. 
//  If month is valid but year is not, returns -1 
//  If month is invalid, but year is not, returns -2 
//  If month and year are valid, but otherwise failed, returns -3 
int getMonthArray(int month, int year, vector<Date>& monthArray); 
0

简单的

实施例,通过将载体和成功返回bool

bool getMonthArray(std::vector<Date>* out, int month, int year); 

在您的实现中,如果参数无效,则返回false。

1

有极少数的选择:

  1. 返回指示错误的正常返回类型的特殊价值。
  2. 更改返回到错误代码(或标志)并具有输出参数(参考或指针)。
  3. 返回既包含值又包含错误指示符的包装(例如:Boost.Optional)。
  4. 抛出异常。
  5. 有无法无效的参数。

选项1到4是非常明显的。

选项5并不总是可能的,但参数类型(包括枚举),并解释仔细选择在某些情况下工作。

不知道你的功能在做什么,这里有一些建议:

a。改变月份&一年的类型为unsigned。 b。将“月”解释为连续的:

vector<Date> getMonthArray(unsigned int month, unsigned int year) { 
    year = year + month/12; 
    month = month % 12; 
    ...