0

I have following code:

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

How can I free ostringstream?

user2036891
  • 231
  • 3
  • 5
  • 11

4 Answers4

4

With lifetime management:

std::string query;
int n = 2;

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

Shorter, but a bit tougher to read:

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

Possibly better, depending on your situation:

auto query = std::to_string(2);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

Just let it go out of scope:

int n=2;
string query;
{
    ostringstream convert;
    convert << n;
    query = convert.str();
}
Michael Wild
  • 24,977
  • 3
  • 43
  • 43
0

you don't need to free the stream. the stream is on the stack, so it will destroyed automatically.

peterus
  • 15
  • 5
0

How can I free ostringstream?

If by "free" you mean "deallocate resources" for the instance, then let it go out of scope.

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

If you mean "clear the contents" then you can use:

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();
utnapistim
  • 26,809
  • 3
  • 46
  • 82