Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 运算符重载以构造异常消息_C++_Exception_Operator Overloading_C++03 - Fatal编程技术网

C++ 运算符重载以构造异常消息

C++ 运算符重载以构造异常消息,c++,exception,operator-overloading,c++03,C++,Exception,Operator Overloading,C++03,我正在更改遗留代码库中的一些代码。在这段代码中,有一个经常重复的模式,如下所示: std::stringstream ss; ss << ...; throw MyCustomException(ss.str()); throw MyCustomException() << ...; 这两种解决方案(#if…#endif)都可以工作,但由于所有内容都是按值进行的,因此在抛出异常对象之前会创建大量异常对象的副本。将签名更改为MyCustomException&e会产生大

我正在更改遗留代码库中的一些代码。在这段代码中,有一个经常重复的模式,如下所示:

std::stringstream ss;
ss << ...;
throw MyCustomException(ss.str());
throw MyCustomException() << ...;
这两种解决方案(
#if…#endif
)都可以工作,但由于所有内容都是按值进行的,因此在抛出异常对象之前会创建大量异常对象的副本。将签名更改为
MyCustomException&e
会产生大量编译时错误(为什么?)

由于我绑定到一个只支持C++03的旧GCC版本,整个问题变得更加复杂。所以这里没有花哨的C++1[147]东西

有没有更好的方法来实现我想要的功能(
throw MyCustomException())
[S] 由于所有内容都是按值进行的,所以在抛出异常对象之前会创建很多异常对象的副本

如果异常是exception(),那么运行时丢失不应该是您关心的事情。此外,可能会节省您的时间。概要文件和结论

这就是说,您可以通过使用const ref删除一半的所谓副本:

struct MyCustomException: public std::runtime_error
{
    MyCustomException(const std::string& what_arg="")
    : std::runtime_error(what_arg)
    {}

    template<typename T>
    friend
    MyCustomException operator<<(MyCustomException const& e, T const& obj)
    {
        std::stringstream ss;
        ss << e.what();
        ss << obj;
        return MyCustomException(ss.str());
    }
};
struct MyCustomException:public std::runtime\u错误
{
MyCustomException(const std::string&what_arg=“”)
:std::运行时错误(what_arg)
{}
模板
朋友

MyCustomException运算符表示我没有考虑到
const
引用的事情:/不幸的是,我仍然得到了与以前相同数量的副本,而
friend…const MyCustomException&
。这可能更奇怪。
struct MyCustomException: public std::runtime_error
{
    MyCustomException(const std::string& what_arg="")
    : std::runtime_error(what_arg)
    {}

    template<typename T>
    friend
    MyCustomException operator<<(MyCustomException const& e, T const& obj)
    {
        std::stringstream ss;
        ss << e.what();
        ss << obj;
        return MyCustomException(ss.str());
    }
};