what does something like this do?
static int i;
// wrapped in a big loop
void update_text()
{
std::stringstream ss; // this gets called again and again
++i;
ss << i;
text = new_text(ss.str()); // text and new_text are defined elsewhere
show_text(text); // so is this
}
does is create a new instance of ss in the stack with a new address and everything? would it be smarter to use sprintf with a char array?
Each time the function is called, a new, local, instance of
std::stringstream ssis pushed upon on the stack. At the end of the function, this instance is destroyed and popped off the stack.At no point in time does the scope of function
update_texthave multiple variables in its scope with the identifierss. So, within the scope ofupdate_text, there is only onessidentifier.A character array would make no difference. Each time the function is called, the char array, if statically allocated, will be pushed onto the stack and popped off at the end. If you use dynamic memory and dynamically allocate the character array, the
newanddeletestatements would still be executed each time the function was called, and the pointer to this character array would still be pushed and popped off the stack. Thestd::stringstreamis already handling thenewanddeletefor you internally.Declaring an object multiple times would look like this:
This would cause compiler errors.
Be warned, this however, is valid:
Because the two variables are of different scopes. The second
xexists only within thatifstatement. As such, the compiler can infer that any reference toxafter that declaration and within that scope refers to the secondx. Note that the type doesn’t matter, it’s the identifier or “name” that matters.