C++ std::vector::通过引用推回参数

C++ std::vector::通过引用推回参数,c++,stl,parameters,reference,std,C++,Stl,Parameters,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 dele

考虑以下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
}
vector myFunction()
{
向量向量;
char*szSomething=新字符[7];
strcpy(szSomething,“你好!”);
vRetVal.push_back(szSomething);//这里vRetVal[0]address==&szSomething
删除[]szSomething;//删除[]szSomething将“损坏”vRetVal[0]
szSomething=NULL;
return vRetVal;//这里我返回一个“损坏”的vRetVal
}

你知道如何使用push_back来复制我传递的参数,而不是通过引用获取它吗?任何其他想法都会被接受和欣赏。

您将其指针推到向量的对象会被代码中的
delete
语句破坏。这意味着,向量中的项(即指针)指向已删除的对象。我肯定你不想那样

使用
std::string

std::vector<std::string> myFunction()
{
    std::vector<std::string> v;
    v.push_back("Hello"); 
    v.push_back("World");
    return v;
}
std::vector myFunction()
{
std::向量v;
v、 推回(“你好”);
v、 推回(“世界”);
返回v;
}
在C++11中,您可以编写以下代码:

std::vector<std::string> myFunction()
{
   std::vector<std::string> v{"Hello", "World"};
   return v;
}
std::vector myFunction()
{
向量v{“你好”,“世界”};
返回v;
}
或者这个,

std::vector<std::string> myFunction()
{
   return {"Hello", "World"};
}
std::vector myFunction()
{
返回{“你好”,“世界”};
}
向后推
将复制您传递的参数

但是您的参数是指针,而不是字符串本身


要自动复制字符串,请使用
std::string

失败手动内存管理失败-一如既往。像理智的人一样使用
std::string
,你会发现你的程序实际上有机会正常运行。

push_back()确实可以复制。在您的发布代码中,您将指针传递给空终止的字符串,因此C++复制指针的副本。如果需要该字符串的副本,您可以选择:

如果您坚持使用C风格的以null结尾的字符数组作为字符串,那么只需传入指针而不调用delete[]。当然,由于C++只有手动内存管理,所以必须确保在稍后的适当时间调用DEL[],…< /P>
其他人都会告诉您,另一个选项是简单地使用std::string。它将为您管理内存,并且主要是“正常工作…”

使用
std::string
。如果您想让它保持活动状态,为什么要删除
szSomething
?失败手动内存管理总是失败的。您需要使用匈牙利符号吗?或
返回{“Hello”}:-)@KerrekSB:已添加。谢谢。:-)