std::vector::push_back parameter by reference

c++, parameters, reference, std, stl

Solution

The object whose pointer you've pushed to the vector is destroyed by `delete` statement 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`:

std::vector<std::string> myFunction()
{
    std::vector<std::string> v;
    v.push_back("Hello"); 
    v.push_back("World");
    return v;
}

In C++11, you could just write this:

std::vector<std::string> myFunction()
{
   std::vector<std::string> v{"Hello", "World"};
   return v;
}

Or this,

std::vector<std::string> myFunction()
{
   return {"Hello", "World"};
}

Problem

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.

Original source