STL vector class stores a copy of the object using copy constructor each time I call push_back. Wouldn't it slow down the program? I can have a custom linkedlist kind of class which deals with pointers to objects. Though it would not have some benefits of STL but still should be faster.
See this code below:
#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
class myclass
{
public:
char* text;
myclass(const char* val)
{
text = new char[10];
strcpy(text, val);
}
myclass(const myclass& v)
{
cout << "copy\n";
//copy data
}
};
int main()
{
vector<myclass> list;
myclass m1("first");
myclass m2("second");
cout << "adding first...";
list.push_back(m1);
cout << "adding second...";
list.push_back(m2);
cout << "returning...";
myclass& ret1 = list.at(0);
cout << ret1.text << endl;
return 0;
}
its output comes out as:
adding first...copy
adding second...copy
copy
The output shows the copy constructor is called both times when adding and when retrieving the value even then. Does it have any effect on performance esp when we have larger objects?