c++函数返回值有关问题

c++函数返回值问题
string   fun()
{
return   "some ";
}
///////
情况一
////
const   char*   c   =   fun().c_str();
//////
情况二
string&   str   =   fun();
const   char*   c   =   str.c_str();

///实验结果
情况一
c中存 " "
情况二
c中存 "some "

why?


------解决方案--------------------
c_str();是什么?
------解决方案--------------------
up
------解决方案--------------------
学习
------解决方案--------------------
Remarks
Objects of type string belonging to the C++ template class basic_string <char> are not necessarily null terminated. The null character ' \0 ' is used as a special character in a C-string to mark the end of the string but has not special meaning in an object of type string and may be a part of the string just like any other character. There is an automatic conversion from const char* into strings, but the string class does not provide for automatic conversions from C-style strings to objects of type basic_string <char> .

The returned C-style string should not be modified, as this could invalidate the pointer to the string, or deleted, as the string has a limited lifetime and is owned by the class string.


------解决方案--------------------
广告男
好!
------解决方案--------------------
搞不懂,谁知道的来解释一下
------解决方案--------------------
偶就接分好了
------解决方案--------------------
觉得还是变量生命周期的问题.在子函数中分配的空间,到子函数结束时,它的生命也就走到了尽头.所以结果就会像楼主所看到的
------解决方案--------------------
首先要搞懂函数名fun也是一个指针,那么在情况1当中,const char* c = fun().c_str();这是把fun指针转换成字符型再传给c,此时函数并没有执行,就是说fun只是一个空指针。函数没有被调用,因此你得到的c是个空值。

情况2当中你先让c指向函数fun(),在这个过程中,函数被调用,fun()不再是空指针,fun()指向“some”这个字符串,因此可以用c来取到some。

总体来说你忽略了两种情况的函数调用,情况1没调用,没实例化;情况2调用了函数,所以可以取到some。
你可以在情况2中增加一条语句,变成:string& str = fun();
const char* c = str.c_str();
const char* a = fun();
同样你会看到a也取到了some,因为“string& str = fun();”已经调用了函数fun()。
------解决方案--------------------
匆忙之中写错了呵呵,新加的语句应该是:const char* a = fun.c_str();

相信你应该能看的出来,hoho
------解决方案--------------------
看看再说吧,
------解决方案--------------------
string fun()
{
return "some ";
}
///////
情况一
////
const char* c = fun().c_str();
//////
情况二
string& str = fun();
const char* c = str.c_str();

///实验结果
情况一
c中存 " "
情况二
c中存 "some "

why?

===========================
const char* c = fun().c_str();
c是一个POINTER,在这里没有指向一块内存。
可以这样TRY:
char c[256];
strcpy(c,reinterpret_cast <const char *> (fun().c_str()));

理论东西上面说了很多了,就是STACK已经销毁的缘故。

------解决方案--------------------
呵呵
------解决方案--------------------