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?
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?
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);
Just let it go out of scope:
int n=2;
string query;
{
ostringstream convert;
convert << n;
query = convert.str();
}
you don't need to free the stream. the stream is on the stack, so it will destroyed automatically.
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();