[問題] 開function給別人用遇到的問題

看板C_and_CPP作者 (改)時間12年前 (2012/03/04 11:54), 編輯推噓1(107)
留言8則, 4人參與, 最新討論串1/2 (看更多)
Q1. 某個自己寫的function需要回傳字串給呼叫這個function的使用者(非本人), 看過兩個方法: #define LENGTH 16 int MethodA(char** szHello) { *szHello = new char[LENGTH]; strcpy_s(*szHello, LENGTH, "hello world"); return 0; } int MethodB(char* szHello, int nLength) { strcpy_s(szHello, nLength, "hello world"); return 0; } void SomeoneElse() { char* szString = NULL; MethodA(&szString); cout << szString << endl; delete [] szString; szString = NULL; szString = new char[LENGTH]; MethodB(szString, LENGTH); cout << szString << endl; delete [] szString; cin.get(); } MethodA在function裡面new,需要告知使用者記得要delete, MethodB須告知使用者呼叫之前要先new, 因為在使用者這邊new,使用者自己知道需要做delete, MethodA和MethodB的做法都有看過,哪種方式比較好呢??? Q2. 當你開出一系列的function給別人呼叫,但這些function需要按照一定的順序呼叫, 比方說順序為: EnumerateObj() --> CreateObj --> UseObj() ... 如果使用者不按這個順序呼叫可能會crash,但你又沒辦法預期使用者不會亂呼叫, 你該怎麼預防crash呢???? 我目前想到的是在自己的程式這邊紀錄state,比方說: void UseObj() { if(currentState != READY_TO_USE) { return -1; } ... } 在每個function裡面的一開始,都先檢查目前的state是否可以呼叫這個function, 但又覺得這樣做有點麻煩,不知道有沒有更好的做法???? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.240.150.190

03/04 13:07, , 1F
問題1:原則上讓資源使用者自行分配/回收資源是較妥當的
03/04 13:07, 1F

03/04 13:08, , 2F
問題2:參考一下template method pattern看適不適用
03/04 13:08, 2F

03/04 14:17, , 3F
就不要叫做methodA 改為init, destroy, 以及perform(do)
03/04 14:17, 3F

03/05 22:25, , 4F
THANKS
03/05 22:25, 4F

03/07 10:26, , 5F
template<unsigned length> void func(char(&str[length]))
03/07 10:26, 5F

03/07 10:27, , 6F
這個可以傳char[]進去..而且不用傳長度
03/07 10:27, 6F

03/07 10:28, , 7F
template<unsigned length> void func(char(&str)[length])
03/07 10:28, 7F

03/07 10:28, , 8F
這樣才對
03/07 10:28, 8F
文章代碼(AID): #1FKkTmtV (C_and_CPP)
文章代碼(AID): #1FKkTmtV (C_and_CPP)