【问题标题】:std::vector::push_back parameter by referencestd::vector::push_back 参数引用
【发布时间】:2012-11-18 18:51:06
【问题描述】:

考虑以下 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
}

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

【问题讨论】:

  • 使用std::string
  • 如果你想让szSomething保持活力,为什么要删除它?
  • 失败的手动内存管理一如既往的失败。
  • 需要使用匈牙利符号吗? joelonsoftware.com/articles/Wrong.html

标签: c++ stl parameters reference std


【解决方案1】:

您已将其指针推送到向量的对象被代码中的delete 语句销毁。这意味着,向量中的项目(即指针)指向已删除的对象。我确定你不希望这样。

使用std::string:

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

在 C++11 中,你可以这样写:

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

或者这个,

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

【讨论】:

  • return { "Hello" }; :-)
  • @KerrekSB:已添加。谢谢。 :-)
【解决方案2】:

push_back 复制您传递的参数。

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

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

【讨论】:

    【解决方案3】:

    push_back() 确实制作一个副本。在您发布的代码中,您传递了一个指向以空字符结尾的字符串的指针,因此 C++ 制作了 指针的副本。如果想要该字符串的副本,您有一些选择:

    如果你坚持使用 C 风格的空终止字符数组作为字符串,你可以简单地传入指针,not 调用 delete[]。当然,由于C++只有手动内存管理,所以一定要在适当的时候调用delete[]...

    正如其他人会告诉你的那样,另一种选择是简单地使用 std::string。它将为您管理内存,并且大部分时间都“正常工作......”

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2013-10-15
        • 2021-06-18
        • 2023-03-21
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-21
        • 1970-01-01
        相关资源
        最近更新 更多