[問題] 在struct宣告dynamic array的問題

看板C_and_CPP (C/C++)作者 (低調boy)時間13年前 (2013/04/05 11:03), 編輯推噓3(3027)
留言30則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) ubuntu 12.04 問題(Question): 用vector宣告不確定大小的struct array 此struct有dynamic array 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> typedef struct Test{ int n; char* test; Test(int); ~Test(); }Test; Test::Test(int i){ n = i; test = (char*)malloc(sizeof(char) * n); } Test::~Test(){ free(test); } int main() { int i; scanf("%d",&i); std::vector<Test> test(i,Test(10)); printf("%d\n",test[1].n); return 0; } 補充說明(Supplement): 好像宣告完後 就會馬上進入 desctructor @@ 所以Memory就會出錯 假如不要宣告dynamic array就不會有錯誤= = 怎麼會降.... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.45.237.106

04/05 11:20, , 1F
Test() : test(0) {} 加進去吧
04/05 11:20, 1F

04/05 11:22, , 2F
還有那個 typedef 是多餘的
04/05 11:22, 2F

04/05 11:23, , 3F
真是抱歉我打錯了
04/05 11:23, 3F

04/05 11:24, , 4F
Test() : n(0), test(0) {} 才對,忘記還有一個
04/05 11:24, 4F

04/05 11:25, , 5F
可以搜尋 zero initialization
04/05 11:25, 5F

04/05 11:40, , 6F
話說,雖然你可能用Test(int i=0) 這樣的方式會通過,
04/05 11:40, 6F

04/05 11:41, , 7F
但我覺得你最好還是不要這樣用
04/05 11:41, 7F

04/05 11:44, , 8F
因為可能會在某一天某一台機器上出現想都想不到的錯誤
04/05 11:44, 8F

04/05 11:50, , 9F
std::vector<Test> test(i,Test(10));這行我也覺得有錯
04/05 11:50, 9F

04/05 11:52, , 10F
我覺得你用一個 member function 去 malloc memory
04/05 11:52, 10F

04/05 11:53, , 11F
不要在 ctor 裡面去 malloc 比較好
04/05 11:53, 11F

04/05 12:03, , 12F
What the hack is applecool talking about? Implement
04/05 12:03, 12F

04/05 12:03, , 13F
copy constructor and operator= should solve the problem.
04/05 12:03, 13F

04/05 12:21, , 14F
我只是覺得用一個 ptr 複製如果被別人釋放了
04/05 12:21, 14F

04/05 12:22, , 15F
就可能會導致重複free了,如果每次都 copy array 又太慢
04/05 12:22, 15F

04/05 12:22, , 16F
加個計數器又覺得太複雜,把情況盡量簡單有效率就好了
04/05 12:22, 16F

04/05 12:24, , 17F
但是確實如果只是把 malloc 移出來還是可能會有重複free
04/05 12:24, 17F

04/05 12:25, , 18F
最好還是把 free dtor 也移出來好了
04/05 12:25, 18F

04/05 12:26, , 19F
我是說 free 移出 dtor, 由 user 自己控制記憶體
04/05 12:26, 19F

04/05 12:53, , 20F
user自己控制的話那幹嘛寫class,直接malloc就好啦
04/05 12:53, 20F

04/05 12:54, , 21F
封裝這些複雜的操作是class的責任
04/05 12:54, 21F

04/05 12:55, , 22F
這邊明顯就是dtor、copy-ctor、operator= 三位一體原則
04/05 12:55, 22F

04/05 12:55, , 23F
那用 string
04/05 12:55, 23F

04/05 13:05, , 24F
很多 string 都有內建計數器
04/05 13:05, 24F

04/05 13:06, , 25F
不過不是一定
04/05 13:06, 25F

04/05 13:10, , 26F
不過我覺得有時候 reference count 會拖到速度
04/05 13:10, 26F

04/05 13:11, , 27F
所以覺得這樣小而操作簡單的程式不要用 reference count
04/05 13:11, 27F

04/05 13:14, , 28F
因為如果很少必須複製,或者複製成本很低的話~我想
04/05 13:14, 28F

04/05 13:16, , 29F
所以我建議移出,struct 單純包住 int & char *
04/05 13:16, 29F

04/05 13:17, , 30F
我是說 變數 n 和 pointer test, & 是 and XD
04/05 13:17, 30F
文章代碼(AID): #1HNZxbX9 (C_and_CPP)
文章代碼(AID): #1HNZxbX9 (C_and_CPP)