Runtime error while implementing vector in c++ -


i trying implement own version of vector in c++. far have done this..

#include<iostream> #include<string>  using namespace std;   template<class t> class vec { public:     t *a;     int i,n;     vec(int n=0):n(n)     {         i=-1;         a=(t *)malloc(n*sizeof(t));     }     void push_back(const t& t);     t at(const int& index) const; };  template<class t> void vec<t>::push_back(const t& t) {     if(++i==n)     {         a=(t *)realloc(a,(++n)*sizeof(t));     }     a[i]=t; }  template<class t> t vec<t>::at(const int& index) const {     return a[index]; }  int main() {     vec<string> v;     v.push_back("2");     v.push_back("1");     v.push_back("3");     cout<<v.at(0)<<endl;     return 0; } 

but getting run time error when run error in above code? using c++ , visual studio run.

in case need use placement new.

something this:

// allocate memory void* mem = malloc(sizeof(std::string));  // call constructor via placement new on allocated memory std::string* ptr = new (mem) std::string(); 

but then, forced explicitly call destructor memory

ptr->~std::string(); 

overall - not way achieve want. it's more convenient use usual new\delete operators , copy internal data on re-allocation (how done in stl vector)


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -