Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens with member of class during erasing from vector?

Tags:

c++

vector

Below there is code, which makes me confused :

class Simple{

  private:
    int m_nID;

  public:
    Simple(int nID) {
     m_nID = nID;
    }

   ~Simple() {
     std::cout << "Destructing Simple " <<  m_nID << std::endl;
    }

    Simple(const Simple& other) { 
     m_nID = other.m_nID;
    };  
 };

 int main(){
    Simple Simple1(1); // allocating on stack
    Simple Simple2(2); //
    Simple Simple3(3); //
    std::vector<Simple>  m;

    m.push_back(Simple1);  //
    m.push_back(Simple2);  // copy constructor called
    m.push_back(Simple3);  //
    std::cout << "\n------ ERASING ELEMENTs FROM VECTOR-------" << std::endl;
    m.erase(m.begin()); //
    m.erase(m.begin()); // destructor called
    m.erase(m.begin()); //
    std::cout << "\n------ After ERASING ELEMENT FROM VECTOR-------" << std::endl;
    return 0;
 } 

Why these three lines:

   m.erase(m.begin());
   m.erase(m.begin());
   m.erase(m.begin());

cause this output:

   Destructing Simple 3
   Destructing Simple 3
   Destructing Simple 3

Why m_nID is always 3 ? For each push_back copy constructor copy 1,2,3 to m_nID, so shouldn't be:

    Destructing Simple 1  // or 3
    Destructing Simple 2  // or 2
    Destructing Simple 3  // or 1

?

like image 480
maciekm Avatar asked Jan 28 '26 16:01

maciekm


2 Answers

How does std::vector remove the first element? It copies all of the elements down one (using assignment), and then destructs the last. Try instrumenting the copy constructor and assignment as well, and you'll see what's happening. (You may also see some unexpected copies when doing the push_back, if the vector has to increase its capacity.)

like image 128
James Kanze Avatar answered Jan 31 '26 06:01

James Kanze


When erasing the first element, only one element (the last) is destroyed. The other elements are assigned from back to front, before:

Initial state:     1, 2, 3
State after copy:  2, 3, 3
State after erase: 2, 3
State after copy:  3, 3
State after erase: 3
Final state:       [empty]

3 is always the last.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!