代码之家  ›  专栏  ›  技术社区  ›  Alexis Wilke

为什么tellp()是非常量?

  •  1
  • Alexis Wilke  · 技术社区  · 5 年前

    我正在研究一个日志,它有一个消息继承 std::stringstream .

    当我想打印消息时,我调用一个函数,该函数将消息作为 const :

    void logger::log_message(message const & msg)
    

    在该函数中,我想检查是否有任何内容写入了消息。如果没有,我可以忽略这个电话。我使用以下内容:

    if(const_cast<message &>(msg).tellp() == 0)
    {
        return;
    }
    

    我不得不使用 const_cast<>() 因为 tellp() 不是 康斯特 . 我想知道的是为什么检索当前的搜索位置会对流产生副作用。我能理解 seekp() 它改变了位置,但不是 Telp() . 这可能是规格上的错误吗?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Enosh Cohen    5 年前

    如果失败,tellp()将更改对象的rdstate。

    见: https://en.cppreference.com/w/cpp/named_req/UnformattedOutputFunction