Using static equivalant ?

J

joseph cook

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?
 
V

Victor Bazarov

joseph said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top