![]() |
Using static equivalant ?
Is the following code:
void foo() { static std::vector<int> obj (500); obj.clear(); } mostly equivalant in operation to the following: void foo() { static bool firstTimeCalled = true; std::vector<int> obj; if(firstTimeCalled) { obj.resize(500); firstTimeCalled = false; } obj.clear(); } With regards that I am only allocating memory for the 500 ints once, no matter how many times this function is called? |
Re: Using static equivalant ?
joseph cook wrote:
> Is the following code: > > void foo() > { > static std::vector<int> obj (500); > obj.clear(); > > } > > mostly equivalant in operation to the following: > > void foo() > { > static bool firstTimeCalled = true; > std::vector<int> obj; > if(firstTimeCalled) > { > obj.resize(500); > firstTimeCalled = false; > } > obj.clear(); > } Yes, looks like it. > With regards that I am only allocating memory for the 500 ints once, > no matter how many times this function is called? It's guaranteed that 'clear' doesn't shrink the allocated vector storage, so, yes, it should be keeping the 500 reserved. You might want to use 'reserve' instead, maybe: static std::vector<int> obj; static int dummy = (obj.reserve(500), 42); although for 'int' it probably doesn't matter. You still need to 'clean' it at some point, right? V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask |
| All times are GMT. The time now is 08:37 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.