views:

131

answers:

2

IDE - Visual Studio 2008, Visual C++

  1. I have a custom class Class1 with a copy constructor to it.
  2. I also have a vector
  3. Data is inserted using the following code
 Class1* objClass1;
 vector<Class1> vClass1;

 for(int i=0;i<1000;i++) {

    objClass1 = new Class1();
    vClass1.push_back(*objClass1);
    delete objClass1;

}

Now on every insert, the vector gets re-allocated and all the existing contents are copied to new locations. For example, if the vector has 5 elements and if I insert the 6th one, the previous 5 elements along with the new one gets copied to a new location (I figured it out by adding log statements in the copy constructors.)

On using reserve(), this however does not happen as expected! I have the following questions

  1. Is it mandatory to always use the reserve statement?
  2. Does vector does a reallocation every time I do a push_back; or does it happen because I am debugging?
+1  A: 
  1. It's not mandatory, it's an optimization because reallocating is expensive.
  2. I think it's an implementation detail how often it reallocates. I think it's normal for the vector to double its storage every time it reallocates, but, as I said, this can vary by implementation. (It might be the case that because you are in a debug build it's reallocating more often than normal.)
jwismar
@jwismar: No, his memory handling is fine. Vector will contain a *copy* of `*objClass1`, so it is perfectly legal to delete the original.
doublep
A: 

Find out by putting your copy constructor test into non debug code, and let us know what you get for your platform! IMO the vector shouldn't reallocate on every pushback. There are smarter ways to manage memory, and I'd bet money that the implementers didn't do that.

Joshua