Consider the following source code in C++
vector <char *> myFunction()
{
vector <char *> vRetVal;
char *szSomething = new char[7];
strcpy(szSomething,"Hello!");
vRetVal.push_back(szSomething); // here vRetVal[0] address == &szSomething
delete[] szSomething; // delete[]ing szSomething will "corrupt" vRetVal[0]
szSomething = NULL;
return vRetVal; // here i return a "corrupted" vRetVal
}
Any idea on how to use push_back to make a copy of the parameter I pass instead of taking it by reference? Any other idea is also accepted and appreciated.
The object whose pointer you’ve pushed to the vector is destroyed by
deletestatement in your code. That means, the item (which is pointer) in the vector is pointing to a deleted object. I’m sure you don’t want that.Use
std::string:In C++11, you could just write this:
Or this,