[問題] 開function給別人用遇到的問題
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
03/04 13:07, 1F
→
03/04 13:08, , 2F
03/04 13:08, 2F
→
03/04 14:17, , 3F
03/04 14:17, 3F
→
03/05 22:25, , 4F
03/05 22:25, 4F
推
03/07 10:26, , 5F
03/07 10:26, 5F
→
03/07 10:27, , 6F
03/07 10:27, 6F
→
03/07 10:28, , 7F
03/07 10:28, 7F
→
03/07 10:28, , 8F
03/07 10:28, 8F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):