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

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

问题描述

在一个库中,我有一个函数可以在数据库中搜索一个键并返回一个对对象的非常量引用.我想处理没有找到密钥的情况,这通常是由于调用函数时出错引起的.这种情况非常糟糕,以至于程序无法继续运行,因此我打印了一条消息以帮助发现错误并调用 exit(1).问题在于 return 语句在这种情况下永远不会执行,但无论如何都必须存在.如果它是一个指针,我可以 return 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
";
     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)

没有.如果此代码是库的一部分,则库不应决定应用程序是否应该退出.

No. If this code is part of a library, the library should not be the one deciding if the application should exit or not.

如果一个文件打开并且需要关闭,或者需要清理其他一些资源,或者如果您的 DB 类的用户想要记录错误并继续执行其他操作,该怎么办?

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天全站免登陆