我傳遞一個矢量指向使用該指針其推動數據的另一功能:傳遞一個矢量指向一個函數導致段錯誤
void foo(vector<pair<int,int>> * vp){
vp->push_back(pair<int,int>(1,1)); //causes segfault
}
void bar(vector<pair<int,int>> *vp = NULL){
foo(vp);
}
的的push_back導致段錯誤。
我傳遞一個矢量指向使用該指針其推動數據的另一功能:傳遞一個矢量指向一個函數導致段錯誤
void foo(vector<pair<int,int>> * vp){
vp->push_back(pair<int,int>(1,1)); //causes segfault
}
void bar(vector<pair<int,int>> *vp = NULL){
foo(vp);
}
的的push_back導致段錯誤。
如果疼,不要這樣做。你幾乎不應該使用指針來傳遞像向量這樣的東西 - 使用引用代替:
void foo(vector<pair<int,int>> & vp){
vp.push_back(pair<int,int>(1,1));
}
同意,通過參考通常是更好的解決方案 – 2011-06-14 05:44:02
我不同意;使用非const引用是一種糟糕的風格,因爲您無法猜測看到您傳遞的參數是可變的代碼。 – grep 2013-03-16 17:05:34
我猜你的矢量是NULL ...你會想在foo中添加一個檢查。
void foo(vector<pair<int,int>> * vp)
{
if (vp != NULL)
vp->push_back(pair<int,int>(1,1));
}
如果您在編譯器中支持C++ 0x,也更喜歡使用nullptr
。
你叫'bar'怎麼樣?你的調試器說什麼? – 2011-06-13 20:02:30
通過引用傳遞向量。那它永遠不會是NULL。 – 2011-06-13 20:24:52