看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《realmojo (蟹老闆)》之銘言: : #include <vector> : #include <iostream> : using namespace std; : class Bin; : vector<Bin> *v; : struct Bin { : int *glass; : Bin():glass(new int(0)) {} : }; : int main() { : v = new vector<Bin>(2); : *(v->at(0).glass) = 9; : cout << *(v->at(1).glass) << endl; : } : 為什麼output會是9而不是0? 順便一提, 你這裡的用法有很多看起怪怪的地方 比如, 一般 int, double 這類東西絕少要這樣 allocate from heap. 當然, 你 new 了也沒有相對應的 delete, 沒有 正確的 copy ctor 和 assignment operator 也是 問題. 通常這類 class 會直接寫 struct Bin { int glass; Bin():glass(0){} }; 就夠了 (impl 其實分開寫更好) vector 也是, 這裡也看不出有什麼需要 new vector<Bin>(2); 直接在main 裡面 vector<Bin> v(2); 不就好了? 用起來也更簡單: v[0].glass = 9; 或 v.at(0).glass = 9; 這都比你現在的寫法易讀太多了 (也更少問題). alien -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 202.155.236.82
chrisdar:我測試他的Code時還需要把Visual Leak Detector關掉才行 02/03 11:08
realmojo:我的code是從一個完整的code發現bug,慢慢debug,刪除後 02/03 11:20
realmojo:變成最精簡的程式才po上來問的,不是原先就這麼寫的 02/03 11:21
realmojo:不過還是感謝,我本身的確沒有delete的習慣 02/03 11:22
adrianshum:delete 這種已經不可以用 "習慣" 來帶過了. 這是非做不 02/03 11:45
adrianshum:可的東西了啦... 02/03 11:45
StubbornLin:我在po程式問問題時也會把程式簡化再貼 02/03 13:46
StubbornLin:畢竟問題只在一個範圍內 常常在簡化的過程中 02/03 13:46
StubbornLin:就自己找到問題在哪裡 02/03 13:46
james732:會簡化貼 +1 02/03 13:48