>>Now my guess is that the first block of code uses more memory at any given moment than the second one
In the second example, a good optimizing compiler will notice that it only needs to allocate space for one std::string object and reuse this memory on each block entry. All memory is allocated on the stack during function entry, not block entry. That makes the second example more memory efficient than the first. It would be the same as declaring one std::string object at the beginning of the function and re-using it in each block, something like this: (in this example you don't need the blocks at all!)
int foo()
{
std::string str;
{
str = "Hello";
// blabla
}
{
str = "By";
// blabla
}
}
>>And each mystring only has scope within the {} enclosing it right?
That is correct -- but it doesn't mean that the memory allocated for the objects are removed from the stack when the block terminates. It is only released when the function returns to whoever called it.
>>the second block of code uses more than or equal processing power than the first one
Depends on how you look at it. Overall, from the beginning to the end of the function they are both equal. But the second will consume lessinitial processing than the first because std::string class constructor will be called for all three strings at the same time in the first example, while the constructors are called only duirng block entry in the second example.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343