使用可能引发c++的函数初始化const对象

Initializing a const object with a function that may throw c++

本文关键字:函数 初始化 const 对象 c++      更新时间:2023-10-16

我正在编写一个函数,该函数调用一个可能抛出的函数来初始化const成员。问题是:如果我把初始化放在try块中,当它超出范围时就会被删除。如果我把初始化放在try块之外,我就无法捕获异常。解决方法是:

double functionA()
{
  double a;
  try
  {
    a=functionThatMayThrow();
  }
  catch(std::except&p)
  {
    std::throw_with_nested(std::runtime_error(__func__);
  }
  const double b=a;
  //More code that uses b and computes x
  return x; 
}

我想知道是否有更好的方法。类似于:

double functionA()
{
  const double b=functionThatMayThrow();
  //catch the exception somehow and rethrow with nested information
  //Unchanged
  //More code that uses b and computes x
  return x; 
}

也许我只是对这个问题采取了一种完全错误的方法。你能给我一些建议吗?任何boost或c++11相关的解决方案也是不错的。

要向任何传递的异常添加一些跟踪信息,1可以这样做:

auto func_A()
    -> double
{
    try
    {
        // The complete original function body.
        double const a = 2*some_func();
        return a/2;
    }
    catch( ... )
    {
        throw_with_nested( runtime_error( __func__ ) );
    }
}

但是,在任何地方重复这一点都可能有点乏味且容易出错,因此您可能希望集中逻辑,而将函数表示为例如

auto func_A()
    -> double
{
    return with_trace( __func__, [&]() -> double
    {
        // The complete original function body.
        double const a = 2*some_func();
        return a/2;
    } );
}

现在,这需要一些支持机制,包括下行呼叫和上行呼叫,例如

#include <exception>    // std::throw_with_nested
#include <iostream>
#include <stdexcept>    // std::runtime_error, std::exception
#include <stdlib.h>     // EXIT_FAILURE, EXIT_SUCCESS
#include <string>       // std::string
#include <vector>       // std::vector
namespace cppx {
    using std::runtime_error;
    using std::throw_with_nested;
    template< class Func >
    auto with_trace( char const* const func_name, Func const body )
        -> decltype( body() )
    {
        try
        {
            return body();
        }
        catch( ... )
        {
            throw_with_nested( runtime_error( func_name ) );
        }
    }
    namespace x_io
    {
        using std::endl;
        using std::exception;
        using std::cerr;            // For client code.
        using std::ostream;
        using std::rethrow_if_nested;
        namespace impl {
            void print_on( ostream& stream, exception const& x, bool const is_nested )
            {
                stream << (is_nested? ">" : "!") << x.what() << endl;
                try
                {
                    rethrow_if_nested( x );
                }
                catch( exception const& nested_x )
                {
                    print_on( stream, nested_x, true );
                }
                catch( ... )
                {
                    stream << "<unknown exception type>" << endl;
                }
            }
        }  // namespace impl
        auto operator<<( ostream& stream, exception const& x )
            -> ostream&
        {
            impl::print_on( stream, x, false );
            return stream;
        }
    }    // namespace x_io
}  // namespace cppx
namespace my {
    using std::runtime_error;
    using std::string;
    using std::vector;
    using cppx::with_trace;
    bool fail_is_good;
    auto some_func()
        -> double
    {
        if( fail_is_good ) { throw runtime_error( "some_func" ); }
        return 3.14;
    }
    auto func_A()
        -> double
    {
        return with_trace( __func__, [&]() -> double
        {
            double const a = 2*some_func();
            return a/2;
        } );
    }
    void cpp_main( vector< string > const& args )
    {
        using std::cout; using std::endl;
        my::fail_is_good = (args.size() > 1);
        cout << func_A() << endl;
    }
}  // namespace my
auto main( int argc, char* argv[] )
    -> int
{
    using std::exception; using std::string; using std::vector;
    try
    {
        my::cpp_main( vector<string>( argv, argv + argc ) );
        return EXIT_SUCCESS;
    }
    catch( exception const& x )
    {
        using namespace cppx::x_io;
        cerr << x << endl;
    }
    return EXIT_FAILURE;
}

1)不幸的是,Visual C++12.0(2013),即使在2013年11月的CTP版本中,也不支持std::throw_with_nested。只需实现它就可以很容易地添加这种支持。此外,我记得它不支持__func__,但该宏也很容易定义