ein*_*ica 7 c++ error-handling idioms idiomatic
我将用C++开始这个新项目,并且正在考虑一种不痛苦的错误处理方法.现在,我不打算开始抛出和捕获异常,并且很可能永远不会抛出异常,但我在想 - 即使是常规错误处理,为什么要自己滚动/复制粘贴一个类来描述错误/状态,当我可以使用std::exception
它的子类(或者也许是一个std::optional<std::exception>
)?
using Status = std::optional<std::exception>;
Status somethingThatMayFail(int x);
Run Code Online (Sandbox Code Playgroud)
有人/任何项目是这样工作的吗?这是一个荒谬的想法还是有点吱吱作响?
我认为仅性能可能会出现问题。考虑以下代码:
#include <iostream>
#include <chrono>
#include <ctime>
#include <stdexcept>
#include <boost/optional.hpp>
int return_code_foo(int i)
{
if(i < 10)
return -1;
return 0;
}
std::logic_error return_exception_foo(int i)
{
if(i < 10)
return std::logic_error("error");
return std::logic_error("");
}
boost::optional<std::logic_error> return_optional_foo(int i)
{
if(i < 10)
return boost::optional<std::logic_error>(std::logic_error("error"));
return boost::optional<std::logic_error>();
}
void exception_foo(int i)
{
if(i < 10)
throw std::logic_error("error");
}
int main()
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
for(size_t i = 11; i < 9999999; ++i)
return_code_foo(i);
end = std::chrono::system_clock::now();
std::cout << "code elapsed time: " << (end - start).count() << "s\n";
start = std::chrono::system_clock::now();
for(size_t i = 11; i < 9999999; ++i)
return_exception_foo(i);
end = std::chrono::system_clock::now();
std::cout << "exception elapsed time: " << (end - start).count() << "s\n";
start = std::chrono::system_clock::now();
for(size_t i = 11; i < 9999999; ++i)
return_optional_foo(i);
end = std::chrono::system_clock::now();
std::cout << "optional elapsed time: " << (end - start).count() << "s\n";
start = std::chrono::system_clock::now();
for(size_t i = 11; i < 9999999; ++i)
exception_foo(i);
end = std::chrono::system_clock::now();
std::cout << "exception elapsed time: " << (end - start).count() << "s\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我的 CentOS 上,使用 gcc 4.7,它的时间为:
[amit@amit tmp]$ ./a.out
code elapsed time: 39893s
exception elapsed time: 466762s
optional elapsed time: 215282s
exception elapsed time: 38436s
Run Code Online (Sandbox Code Playgroud)
在普通设置中,并且:
[amit@amit tmp]$ ./a.out
code elapsed time: 0s
exception elapsed time: 238985s
optional elapsed time: 33595s
exception elapsed time: 24350
Run Code Online (Sandbox Code Playgroud)
在-O2 设置。
PS 我个人会使用异常/堆栈展开,因为我相信它是 C+ 的基本部分,可能正如 @vsoftco 上面所说。
归档时间: |
|
查看次数: |
343 次 |
最近记录: |