c++ - Templates. adding , getting element char* -
i've got problem template class , using char*. storage elements in class , try add or element ,but segmentation fault appear. possible without class specialisation type char* ?
edit 1: let's assume can't change code in main function class , methods, without specialisations. possible handle char* ? ;)
#include <iostream> #include <vector> using namespace std; template<class t> class test { public: void additem(t element){ elements.push_back(element); } t getitem(int i){ return elements[i]; } vector<t> elements; }; int main() { char * cpt[]={"tab","tab2","tab3"}; test<char*> test1; test1.additem(cpt[1]); char * item=test1.getitem(0); //segmentation fault // done without specialisation class char* ? item[0]='z'; cout<<item<<endl; for(auto v:test1.elements) cout<<v<<endl; return 0; }
you're trying modify constant string literal. gives undefined behaviour; typically segmentation fault, if literal stored in write-protected memory.
in modern c++, program shouldn't compile, since deprecated conversion string literal non-const char*
forbidden in c++11.
if want store modifiable strings, you're best off std::string
.
Comments
Post a Comment