string類的秘密

2021-04-24 01:25:12 字數 561 閱讀 2444

最近想要寫一些跨平台的公用函式,在windows下,作為.dll;在linux下,作為.so檔案使用;所以,想用一些通用的資料型別作為函式引數,但是char* 或者const char* 都很不好用,主要是不方便,不得不型別轉換來轉換去的。所以,就採用string&作為引數,如 dllapi    string& encrypt(string& cpttxt,const char* clrtxt,const char* keyt);之類的函式。

但是,這樣,在呼叫時,如果cpttxt事先沒有儲存過足夠長的字串,而是採用預設例項化得到的變數,又若clrtxt的長的過長,比如超過15(>=16)時,執行就會出錯,報記憶體讀寫錯誤。

經過分析,初步估計是:string的預設長度是16,即是當你呼叫 string str;時,分配的記憶體空間是16位;但是,當你在dll中給其賦值時,如果長度超過了16,string類的內部機制就會作用,即分配記憶體,以增加長度來接收賦值,這樣,dll內部就就分配了記憶體附加給外部傳進來的string;當呼叫返回,到達外部後,如果原先傳進去的是乙個區域性變數,現在要是釋放這個區域性變數的話,其中有一部分是dll中的記憶體,****, 不出錯才怪哦...

String 類的實現(3)String類常用函式

1 2 include3 include4 include5 include 6 using namespace std 自己模擬實現的部分相關c string庫函式 8int my strlen const char p 9 17return count 18 19char my strcopy ...

string類的實現

參考c primer.string類的實現,清翔兔 06,jan.includeusing namespace std class string string void private char m data inline string string const char str inline st...

String類的實現

學習資料結構寫了乙個string的類,貼出來求指教 ifndef string h h define string h h include include include define defaultsize 128 class string maxsize為傳入引數的string string c...