c++ - 我可以扔流吗?

标签 c++ exception iostream ostream

我正在尝试开发一个允许收集相关数据流样式的异常类。

正在关注 Custom stream to method in C++?我扩展了自己的类(class):

class NetworkException : public std::exception, public std::ostream

从流中选取错误数据,然后返回通过 .what() 获取的任何内容。

然后我尝试了这样的事情:

try {
    ssize_t ret = send(sock, headBuffer, headLength, MSG_MORE);

    if (ret <= 0)  throw NetworkException() << "Error sending the header: " << strerror(errno);

    // much more communication code

} catch (NetworkException& e) {
    connectionOK = false;
    logger.Warn("Communication failed: %s",e.what());
}

但是编译器产生错误:

HTTPClient.cpp:246:113: error: use of deleted function 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)'

(这是带有 throw 的那一行。)

我知道流没有复制构造函数,但我认为捕获一个引用而不是对象就足够了。我该如何克服这个问题 - 我可以抛出一个“吞噬”流的物体吗?

最佳答案

你想做的事情已经被很多人尝试过了。这当然是可能的,但需要一些技巧(类似于制作流式记录器所需的技巧)。

事实证明这也是一个坏主意,因为:

  1. 它将流的概念与异常的概念相结合。

  2. 用一个模板函数可以更简单地完成

事实上,这里有 3 个非常简单的替代方案:

#include <iostream>
#include <sstream>
#include <exception>
#include <stdexcept>
#include <boost/format.hpp>

template<class...Args>
std::string collect(Args&&...args)
{
    std::ostringstream ss;
    using expand = int[];
    void(expand{0, ((ss << args), 0)...});
    return ss.str();
}

struct collector : std::ostringstream
{
    operator std::string() const {
        return str();
    }
};

// derive from std::runtime_error because a network exception will always
// be a runtime problem, not a logic problem
struct NetworkException : std::runtime_error
{
    using std::runtime_error::runtime_error;
};

int main()
{
    try {
        throw NetworkException(collect("the", " cat", " sat on ", 3, " mats"));

    } catch (const std::exception& e) {
        std::cout << e.what() << std::endl;
    }

    try {
        throw NetworkException(collector() << "the cat sat on " << 3 << " mats");

    } catch (const std::exception& e) {
        std::cout << e.what() << std::endl;
    }

    try {
        throw NetworkException((boost::format("the cat sat on %1% mats") % 3).str());

    } catch (const std::exception& e) {
        std::cout << e.what() << std::endl;
    }


    return 0;
}

预期输出:

the cat sat on 3 mats
the cat sat on 3 mats
the cat sat on 3 mats

最后,可能是最像流的解决方案:

template<class Exception>
struct raise
{
    [[noreturn]]
    void now() const {
        throw Exception(_ss.str());
    }

    std::ostream& stream() const { return _ss; }

    mutable std::ostringstream _ss;
};

template<class Exception, class T>
const raise<Exception>& operator<<(const raise<Exception>& r, const T& t)
{
    using namespace std;
    r.stream() << t;
    return r;
}

struct now_type {};
static constexpr now_type now {};

template<class Exception>
void operator<<(const raise<Exception>& r, now_type)
{
    r.now();
}

调用站点示例:

raise<NetworkException>() << "the cat " << "sat on " << 3 << " mats" << now;

现在使用了 sentinel 以避免任何讨厌的析构函数 jiggery-pokery。

关于c++ - 我可以扔流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37191227/

相关文章:

c++ - Bison C++ 解析器缩放问题

java - Java 中抛出异常的高级概述

Spring MVC : Optional vs Exceptions in Service Layer

c++ - 从输入文件中逐行输入并使用 strtok() 进行标记化,然后输出到输出文件中

c++ - 抽象类类型的无效新表达式

c++ - 数组作为函数参数查找数组长度时出错

c++ - 如何测量并行 C++ 程序中的网络延迟?

c# - 为什么 OdbcCommand.ExecuteScalar() 抛出 AccessViolationException?

c++ - 是否可以修复 iostream cout/cerr 成员函数指针打印为 1 或 true 的问题?

c++ - 测试 stream.good() 或 !stream.eof() 读取最后一行两次