[英]pointer returned to an object turns null after function returns address
我是 CPP 的新手,我正在編寫一個程序來模擬包含目的地的火車路徑系統,並開始使用面向 object 的編程。 我有 2 個班級,如下所示(有一個乘客 class 但不相關):
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();
}
};
我有一個搜索 function 專門用於根據用戶輸入的命令查找起點和目的地,例如:用戶輸入“add_train cityname1 cityname2 <cooldown_time> <travel_time>”。 我的程序檢測城市名稱並搜索一個向量,我用一個城市名稱的鍵命名了車站,並返回一個指向該車站對象的指針(因為 function 中 memory 行為的復雜性,我將其設置為指針)。 function如下:
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;
}}
我的問題是我的搜索功能的怪異行為,當我調試程序時,我看到 function 找到正確的站 object 並返回一個指向它的指針,但是當執行返回到構造函數 ZC1C425268E68385D1AB5074C1 時,它不是隨機的第一個)與起始站相關的指針指向 null 並用垃圾值替換里面的值。 但是在function搜索目標站后它沒有這樣做並且執行是正確的。
有人可以解釋為什么會發生此錯誤嗎? 我的猜測是我對局部變量和指針返回的理解不夠好,而且我在某個地方犯了一個菜鳥錯誤,但我似乎沒有找到它。
PS:我沒有包含完整的代碼,因為它太長了我可以通過附加文件來包含它,如果有必要的話可以評論下來。
Station *station_search(vector<Station> stations, string key)
仔細看這里,你會看到stations
參數是傳值的,也就是說這個function返回后,這個stations
參數會被銷毀。 不會再有了。 它將不復存在。 它將成為一個前參數。
然而,這個station_search
返回一個指向這個向量中某個值的指針。 因此,邏輯規則規定它將返回一個指向已損壞 object 的指針。 以任何方式嘗試取消引用該指針都會成為未定義的行為。
您的其他 class 方法通過引用接收參數,因此您必須已經了解通過值傳遞參數與通過引用傳遞參數之間的區別,因此您應該在這里簡單地做同樣的事情。
在這里,您傳遞了向量的副本,該向量在 function 返回時被銷毀。 此外,如果未找到密鑰,則返回未初始化的指針。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.