我對這也挺有興趣,那幾篇paper,能介紹介紹嗎?
第三題,請查閱信息論有關內容,一般信息論教材第一章,第二章就夠了。
進一步琢磨,我在http://www.cplusplus.com/上查了查c_str的描述,連接為:http:
//www.cplusplus.com/reference/string/string/c_str/
描述如下:
const char* c_str ( )
const;
Get C string equivalent
Generates a null-terminated sequence of characters (c-string) with the
same content as the string object and returns it as a pointer to an
array of characters.
A terminating null character is automatically appended.
The returned array points to an internal location with the required storage
space for this
sequence of characters plus its terminating null-character, but the
values in this array should not be modified in the program and are only
granted to remain unchanged until the next call to a non-constant member
function of the string object.
關鍵位最后一段:(湊乎著翻譯下,大家海涵哈,不要覺得它慘不忍睹哈,^_^)
該函數所返回的指針(數組)指向該字符串的內部(internal)位置,并且該位
置具有足夠存儲空間來存儲該字符序列以及表示結尾的空字符,但是返回數組中的值在程序不應該有任何修改并只應被傳值使用(這里的grant實在譯不好,望
大牛們指教),直到下一次調用該字符串對象的非常(non-const)成員函數。
這一段話再次驗證了樓主的說法。
@OnTheWay
感謝樓主,恩,我驗證了一下,我的理解不正確,不好意思哈,也感謝從你這學到了東西,3Q。
我用下列代碼進行了驗證,在gcc下編譯通過。
#include <iostream>
#include <string>
using namespace std;
int main(){
string CppString("我是一個string啊,咿呀咿呀喲!");
//在這里用c_str()返回了一個CStyle字符串,保存在CStyleString上
char * CStyleString = const_cast< char *>( CppString.c_str() );
//首先驗證一下這個CStyleString的內容是不是正確
cout << CStyleString <<endl;
//然后對CStyleString進行一些改變。
cin >> CStyleString ;
//輸出改變后的CStyleString看看。
cout << CStyleString << endl;
//這時再輸出CppString的內容,它改變了!。
cout << CppString <<endl;
return 0;
}
程序運行如下:
我是一個string啊,咿呀咿呀喲!
我是一個CStyle String啊,咿呀咿呀喲! //這是我的輸入。
我是一個CStyle
我是一個CStyle ……&%¥*&…… //后邊一一堆亂碼,原因請見樓主的帖子。
不對,我又看了看,我覺得樓主的理解似乎有問題,也請指教指教。
strValue.reserve(sizeValue);
bRet = (0 == getenv_s(&sizeValue, const_cast<char*>(strValue.c_str()), sizeValue, strKey.c_str()));
的確是這里有問題,問題的確出在const_cast<char*>(strValue.c_str())這個表達式上。
但是樓主想表達的意思是不是getenv_s()這個函數把strValue這個string類型“強行”當做的了一個字符串來進行處理,這個函數修改strValue的時候,僅僅修改了“一部分”?
我想應該是這樣,const_cast<char*>(strValue.c_str())是這么執行的:
1、strValue.c_str() 這里strValue返回了一個”臨時的“字符串,注意,是臨時的而且是const的,它應該是新開辟了一小段內存用以存儲這個C-Style字符串,而不是把strValue本身當做字符串給返回回去了。
2、使用const_cast<char *>將這個const 并且”臨時的“字符串進行了轉換,轉換成了 非const ,但仍然是臨時的字符串。
3、然后getenv_s()函數會對這個臨時非const的字符串進行一些操作。
4、隨著函數調用的結束,這個臨時的字符串被釋放掉了。
在上邊這個過程中,并沒有對strValue進行任何改變,也正因此在以后才什么都沒有輸出來。
和樓主不一樣的是,getenv_s()根本沒有對strValue進行任何操作。
@陳梓瀚(vczh)
額,可能表述的不太清楚,我是說學數學的痛苦是黑暗,而掌握數學后的用處是黎明,不是指現在國內現狀啦。
我相信數學技能是非常有用,或許會有人覺得她枯燥,不過,這絕對只是黎明前的黑暗而已!