Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector::push_back parameter by reference

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.

like image 504
user1365914 Avatar asked Sep 18 '26 18:09

user1365914


2 Answers

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"};
}
like image 173
Nawaz Avatar answered Sep 21 '26 07:09

Nawaz


push_back will make a copy of the parameter you pass.

But your parameter is the pointer, not the string itself.

To automatically copy the string, use std::string.

like image 26
Timbo Avatar answered Sep 21 '26 07:09

Timbo