I have the following code:
#include <iostream>
#include <vector>
using namespace std;
int counter = 0;
struct vecobj
{
int elem;
vecobj(){ }
vecobj(const vecobj& rhs)
{
counter++;
elem = rhs.elem;
}
};
vector<vecobj> objvec;
int main()
{
vecobj obj1;
obj1.elem = 1;
objvec.push_back(obj1);
objvec.push_back(obj1);
objvec.push_back(obj1);
std::cout <<"copy constructor called "<< counter <<" times\n";
}
My question is that when I push an object into the vector objvec
, I get the copy constructor called 6 times. While I have pushed only three times. I have verified this with the debugger. I am using visual studio 2017 Community Edition. Is it a bug with STL?
I think a related question does not address the problem fully.
No where is it documented that the vector memory has to be reserved before pushing onto it.The pushing of object calling the copy constructor too many (fibonacci(n)) times can have unintended side effects. I think STL code needs
to be changed for the same.