0

I am trying to refresh myself on some C++ programming and I am wondering about the following use of vectors.

If I have the following

#include <iostream>
#include <vector>

//using namespace std;

int main()
{
    std::vector<int> thevector;
    
    std::vector<int> other;
    
    thevector.push_back(2);
    thevector.push_back(3);
    
    for(int i=0; i< thevector.size();i++)
        std::cout<<thevector[i];
    
    std::cout<<std::endl;
    
    other.push_back(100);
    other.push_back(200);
    other.push_back(300);

    thevector = other;

    for(int i=0; i< thevector.size();i++)
        std::cout<<thevector[i];
    
    
    return 0;
}

My questions are:

  1. Is this safe and correct? What if I do this but 1000 times in a loop?
  2. What happens to the values that were in the original thevector when this is written with other? Isn't there the possibility of a memory leak?
KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • 4
    It's perfectly safe and correct (vector would be really badly designed if it were not). The old values are discarded, and any necessary memory will be deleted. A major purpose of vector is to avoid memory leaks, so no need to worry. – john Dec 20 '20 at 09:12
  • I've chosen our canonical FAQ question about copy constructors as a dupe target, where you can find detailed explanations of copying, one of the core concepts in C++. – L. F. Dec 20 '20 at 10:44

0 Answers0