exit() 在函数内部调用,该函数应该返回一个引用

2022-01-05 00:00:00 return reference exit c++

在一个库中,我有一个函数,它在数据库中搜索一个键并返回一个对对象的非常量引用.我想处理找不到key的情况,一般是调用函数时出错.这种情况非常糟糕,程序无法继续,所以我打印了一条消息来帮助发现错误并调用 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.

如果一个文件打开需要关闭,或者其他一些资源需要清理,或者你的数据库类的用户想要记录错误并继续做其他事情怎么办?

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.

相关文章