std :: vector :: push_back参数引用

use*_*914 2 c++ parameters stl reference std

请考虑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
}
Run Code Online (Sandbox Code Playgroud)

关于如何使用push_back来复制我传递的参数而不是通过引用获取它的任何想法?任何其他想法也被接受和赞赏.

Naw*_*waz 7

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;
}
Run Code Online (Sandbox Code Playgroud)

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

std::vector<std::string> myFunction()
{
   std::vector<std::string> v{"Hello", "World"};
   return v;
}
Run Code Online (Sandbox Code Playgroud)

Or this,

std::vector<std::string> myFunction()
{
   return {"Hello", "World"};
}
Run Code Online (Sandbox Code Playgroud)