百战天虫!
我对这也挺有兴趣,那几篇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进行任何操作。
恩,明白,有收获。3Q。
@陈梓瀚(vczh)
额,可能表述的不太清楚,我是说学数学的痛苦是黑暗,而掌握数学后的用处是黎明,不是指现在国内现状啦。
我相信数学技能是非常有用,或许会有人觉得她枯燥,不过,这绝对只是黎明前的黑暗而已!
re: Mesa安装手记--在Ubuntu 9.10 杨帆 2010-03-31 12:20
@雳雳狐
客气客气,我其实才是最菜的……

导航

<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜