exit()调用一个应该返回引用的函数 [英] exit() call inside a function which should return a reference

查看:156
本文介绍了exit()调用一个应该返回引用的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在库中,我有一个函数,它在数据库中搜索一个键,并返回一个对象的非const引用。我想处理没有找到的键的情况,这通常是由调用函数时的错误引起的。这种情况是如此糟糕,程序不能继续,所以我打印一个消息,以帮助发现错误,并调用 exit(1)。问题是返回语句,在这种情况下永远不会执行,但必须有。如果它是一个指针,我可以只是返回nullptr; 但是有参考?我应该做这样的伪代码吗?

In a library I have a function which searches for a key in a database and return a non-const reference to an object. I want to handle the case in which the key is not found, which is typically caused by a mistake when calling the function. This situation is so bad that the program cannot continue, so I print a message to help to spot the bug and call exit(1). The problem is with the return statement which will never be executed in this case, but have to be there anyway. If it was a pointer I could just return nullptr; but with a reference? Should I do something like this pseudo code?

 Type & get(const Key & k) {
     if (my_db.key_exists(k)) {
       return my_db.at(k);
     }
     std::cerr << k << " not found\n";
     exit(1); 
     return *(new Type(some_dummy_parameters));
 }

看起来这么可怕!也许我应该避免这样的功能。请让我知道您的意见!

It looks so awful! Maybe I should just avoid such a function. Please, let me know your opinion!

推荐答案


这种情况太糟糕了,程序无法继续,因此我打印一条消息以帮助发现错误并调用exit(1)

This situation is so bad that the program cannot continue, so I print a message to help to spot the bug and call exit(1)

否。如果此代码是库的一部分,则库不应该是决定应用程序是否应该退出的库。如果文件是打开的并且需要关闭,或者某些其他资源需要清理,或者如果DB类的用户想记录错误并继续执行其他操作,该怎么办?

No. If this code is part of a library, the library should not be the one deciding if the application should exit or not. What if a file is open and needs to be closed, or some other resource needs to be cleaned up, or if the user of your DB class wants to log the error and continue doing something else?

答案是任何 你现在正在做什么。抛出异常,返回错误代码等,但不要在库或类代码中关闭应用程序。

The answer is anything but what you're doing now. Throw an exception, return an error code, etc. but don't close the application down within library or class code.

相信与否,有一个商业数据库库,做了你正在做的事情(关闭应用程序)。他们从他们的库的用户那里得到了很多愤怒的响应,为什么他们意外关闭应用程序。您知道什么 - 给客户的答案是我们认为错误是足够严重,停止应用程序,因为我们的库无法继续正常工作。这不仅是糟糕的推理,它接近傲慢,客户让他们知道。

Believe it or not, there was a commercial DB library that did exactly what you're doing (closing the app down). They got a lot of angry responses from users of their library as to why they're shutting the application down unexpectedly. And you know what -- the answer given to the customers was that "we felt the error was severe enough to stop the application, because our library can't continue to work properly". That is not only bad reasoning, it borders on arrogance, and the customers let them know that.

这篇关于exit()调用一个应该返回引用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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