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; } 

my code

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

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -