【问题标题】:pointer returned to an object turns null after function returns address函数返回地址后,返回对象的指针变为空
【发布时间】:2021-07-14 15:15:01
【问题描述】:

我是 CPP 的新手,我正在编写一个程序来模拟火车路径系统,该系统包括目的地并开始使用面向对象编程。 我有 2 个班级,如下所示(有一个乘客班级,但不相关):


     class Train
    {
    public:
         int cooldown_time;
         int travel_time;
         int time_since_movement;
         int id;
         class Station *start;
         class Station *destination;
         vector<Passenger *> current_passengers;
         string status;
         void add_train(vector<string> commands, vector<Station> stations, vector<Train> &trains)
         {
              travel_time = stoi(commands[THIRD_PART + 1]);
              cooldown_time = stoi(commands[THIRD_PART + 2]);
              status = TSTATUS1;
              start = station_search(stations, commands[SECOND_PART]); // this is where the problem happens
              destination = station_search(stations, commands[THIRD_PART]);
              id = stations.size();
         }
    };
    class Station
    {
    public:
         int tuffy_price;
         string city_name;
         vector<Passenger *> current_passengers;
         vector<Train *> current_trains;
         int id;
         void add_station(vector<Station> &stations, vector<string> &commands)
         {
              tuffy_price = stoi(commands[THIRD_PART]);
              city_name = commands[SECOND_PART];
              id = stations.size();
         }
    };

我有一个搜索功能,专门用于根据用户输入的命令查找起点和目的地,例如:用户输入“add_train cityname1 cityname2 ”。我的程序检测城市名称并搜索我命名为车站的向量,其中的键是城市名称,并返回指向该车站对象的指针(由于函数中内存行为的复杂性,我将其设置为指针)。 功能如下:

Station *station_search(vector<Station> stations, string key)
    {
         Station *dummy;
         for (int i = 0; i < stations.size(); i++)
         {
              if (stations[i].city_name == key)
              {
                   return &stations[i];
              }
         }
         return dummy;
    }} 

我的问题是我的搜索函数的奇怪行为,当我调试程序时,我看到该函数找到正确的站对象并返回一个指向它的指针,但是当执行返回到构造函数时它是随机的(可能不是随机的)将与起始站相关的第一个指针变为空,并将其中的值替换为垃圾值。 但是函数搜索到目的站后并没有这样做,执行是正确的。

有人可以解释为什么会发生此错误吗? 我的猜测是我对局部变量和指针返回的理解不够好,并且我在某个地方犯了一个菜鸟错误,但我似乎没有找到它。

PS:我没有包含完整的代码,因为它太长了我可以通过附加文件来包含它,如果需要的话可以评论。

【问题讨论】:

  • OT:您应该删除dummy,因为它从未初始化并返回nullptr,以便您可以看到何时找不到电台。
  • std::find_if 可能会有所帮助
  • @SimonKraemer 感谢您的提示,我来自 C 背景,我不知道 nullptr 的语法,否则我可能已经忘记了。

标签: c++ c++11 gcc


【解决方案1】:
Station *station_search(vector<Station> stations, string key)

如果仔细看这里,你会看到stations参数是传值传值,也就是说这个函数返回后,这个@987654324 @ 参数将被销毁。不会再有了。它将不复存在。它将成为一个前参数。

然而,这个station_search 返回一个指向这个向量中某个值的指针。因此,逻辑规则规定它将返回一个指向已销毁对象的指针。以任何方式尝试取消引用该指针都会成为未定义的行为。

您的其他类方法通过引用接收参数,因此您必须已经了解通过值传递参数与通过引用传递参数之间的区别,因此您应该在这里简单地做同样的事情。

【讨论】:

  • 我相信这是解决方案,我确实理解通过引用/值传递的概念,但是我没有注意到我犯了这个错误,你能不能提一下为什么函数正确返回第二个指针但只有第一个失败?
  • 中奖数亿次,同样的道理。 Undefined behavior means anything can happen,这可能意味着预期的结果,千载难逢。
【解决方案2】:

在这里,您传递了向量的副本,该副本在函数返回时被销毁。此外,如果未找到密钥,则返回未初始化的指针。

Station *station_search(vector<Station> stations, string key)
{
     for (Station &station :  stations)
     {
          if (stations.city_name == key)
          {
               // Pointer becomes invalid when you leave.
               // Accessing this pointer will cause undefined behavior.
               return &station;
          }
     }
     // This would always cause undefined behavior as dummy was not initialized.
     return nullptr;
}

你应该传入一个引用并初始化dummy

Station *station_search(vector<Station> &stations, string key)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-04
    • 2015-12-02
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 2018-01-01
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多