2010-04-30 54 views
0
class MyClass 
{ 
public: 
    void setVar(const char *str); 
private: 
    std::string mStr; 
    int maxLength; //we only store string up to this length 
}; 

什麼是執行SETVAR當外部代碼很可能在NULL傳遞一個空字符串(最好的辦法,不能改變)?我目前做的有點像:最佳方式來處理存儲在STD(可能爲null)的char * :: string的

void MyClass::setVar(const char *str) 
{ 
mStr.assign(str ? str : "",maxLength); 
} 

但它似乎有點混亂。想法?

+0

假設str是空終止的:假設你將讀取其他地方的字符串值。這段代碼是否需要一個「char const *」或「string」? – Thomas 2010-04-30 10:47:54

+0

你認爲它是如何凌亂? – 2010-04-30 10:49:34

+0

@Thomas,你爲什麼要問?我認爲無論哪種方式,最好是我的新類使用STL ...實際上,我將它從存儲C字符串轉換而來,因爲它使複製對象更加容易出錯......添加了新字段,並且默認情況下不會複製! – 2010-04-30 10:57:34

回答

4

您發佈的代碼是不正確的,因爲它總是會從源字符串讀maxLength字符。特別是,這意味着當str爲NULL時,它將讀取超過空字符串的末尾。假設str爲空終止:

void MyClass::setVar(const char *str) 
{ 
    if (str==NULL) 
     mStr.clear(); 
    else 
     mStr.assign(str, std::min(strlen(str), maxLength)); 
} 
+0

是的,我剛剛意識到在調試string :: assign不工作,我的預期。 – 2010-04-30 10:56:16

2
void MyClass::setVar(const char *str) 
{ 
    if (str) { 
     mStr.assign(str, str + std::min(strlen(str), maxLength)); 
    } else { 
     mStr = ""; 
    } 
} 
+0

什麼是_str + _ std :: min ... – 2010-04-30 13:18:20