Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Using static equivalant ? (http://www.velocityreviews.com/forums/t460858-using-static-equivalant.html)

joseph cook 03-02-2007 05:37 PM

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?


Victor Bazarov 03-02-2007 05:45 PM

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 04:19 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.