Using static equivalant ?

Discussion in 'C++' started by joseph cook, Mar 2, 2007.

  1. joseph  cook

    joseph cook Guest

    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?
     
    joseph cook, Mar 2, 2007
    #1
    1. Advertising

  2. 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
     
    Victor Bazarov, Mar 2, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Natan

    Static vs. non-static connection

    Natan, May 24, 2004, in forum: ASP .Net
    Replies:
    8
    Views:
    7,371
    Sami Vaaraniemi
    May 26, 2004
  2. Ben
    Replies:
    3
    Views:
    460
  3. Paul W

    Static is REALLY Static!

    Paul W, May 3, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    391
  4. Ricardo Palomares Martinez
    Replies:
    2
    Views:
    390
    david.karr
    Apr 28, 2007
  5. Chuck Insight

    What is the WEB equivalant for Console.WriteLine()

    Chuck Insight, Mar 2, 2005, in forum: ASP .Net Web Controls
    Replies:
    14
    Views:
    235
    Chuck Insight
    Mar 5, 2005
Loading...

Share This Page