【问题标题】:How can I free ostringstream?我怎样才能释放 ostringstream?
【发布时间】:2013-01-28 20:39:59
【问题描述】:

我有以下代码:

int n=2;
ostringstream convert;   // stream used for the conversion
convert << n; 
string query= convert.str();

如何释放 ostringstream?

【问题讨论】:

标签: c++


【解决方案1】:

使用生命周期管理:

std::string query;
int n = 2;

{
    std::ostringstream oss;
    oss << n;
    query = oss.str();
}

更短,但更难阅读:

int n = 2;
std::string query
          = static_cast<std::ostringstream &>(std::ostringstream() << n).str();

可能会更好,具体取决于您的情况:

auto query = std::to_string(2);

【讨论】:

    【解决方案2】:

    让它超出范围:

    int n=2;
    string query;
    {
        ostringstream convert;
        convert << n;
        query = convert.str();
    }
    

    【讨论】:

      【解决方案3】:

      您不需要释放流。流在栈上,所以会自动销毁。

      【讨论】:

        【解决方案4】:

        如何释放 ostringstream?

        如果“免费”是指为实例“释放资源”,则让它超出范围。

        int n=2;
        string query;
        {
            ostringstream convert;   // stream used for the conversion
            convert << n; 
            qyuery = convert.str();
        }
        

        如果您的意思是“清除内容”,那么您可以使用:

        int n=2;
        ostringstream convert;   // stream used for the conversion
        convert << n; 
        string query1 = convert.str();
        // clear the contents & reset error bits (thanks @PeterWood)
        convert.str("");
        convert.clear();
        convert << n + 1;
        string query2 = convert.str();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-07-21
          • 2020-04-05
          • 1970-01-01
          • 2014-06-20
          • 2012-08-06
          • 1970-01-01
          • 2023-01-28
          相关资源
          最近更新 更多