2011-05-10 31 views
5

我不知道,但是这不是为我工作即时得到garbege值当我尝试设置从函数返回的std字符串的char *值:如何设置从STD字符串的char *值(c_str())不工作

string foo() 
{ 
    string tmp ="dummy value"; 
    return tmp; 
} 

char* cc = (char *) foo().c_str(); // if i remove the casting im getting error 
// when i print the cc i get garbage 
printf("%s",cc); 

回答

13

cc指向的数据的生命周期与其来自的字符串的生命周期相同(最好 - 如果修改字符串,它甚至更短)。

在你的情况下,foo()的返回值是在cc初始化结束时被破坏的临时值。

为了避免char *cc = foo().c_str()编译错误,你不应该强制转换为char*,您应该切换到const char *cc,因为const char*是什么c_str()回报。但是,这仍然不能解决主要问题。

最简单的修复程序是:

printf("%s", foo().c_str()); // if you don't need the value again later 

const string s = foo(); 
const char *cc = s.c_str(); // if you really want the pointer - since it's 
          // in the same scope as s, and s is const, 
          // the data lives as long as cc's in scope. 

string s = foo(); 
printf("%s", s.c_str());  // if you don't store the pointer, 
          // you don't have to worry about it. 

std::cout << foo(); // printf isn't bringing much to this party anyway. 
9

foo的结果是,得到由char * cc = ...线的端部被破坏的暂时对象。在恒定的基准存储它:

const string& cc = foo(); 
printf ("%s", cc.c_str()); 
+0

+1提供正确的方法。 – 2011-05-10 08:22:09

+0

完全正确; 'const引用'延长了一个右值的生命恰好是一个奇特的规则,'只''记住_value_也会。 (可能用C++ 11中的移动语义进行优化)。 – xtofl 2011-05-10 08:22:58

+0

只要移动语义或RVO在工作中,使用值类型几乎是等价的。但是引用阻止我们依赖编译器优化。 – Xion 2011-05-10 08:26:52

0

的代码片段将调用未定义的行为,因为从呼叫创建的临时std::string在表达的端部被破坏,但其被指向所述销毁对象cc,仍然使用即使在那之后。

1

传递一个内存位置为foo(),并有FOO修改:

void foo (string* _out_newStr) 
{ 
    _out_newStr->assign("dummy string"); //This is wrong -> _out_newStr = "dummy string"; 
    return; 
} 

然后,当您使用“c_str()”的字符串对象的函数将返回一个const char *值,正如已经指出的那样。

+0

-1。错...... – Nawaz 2011-05-10 08:24:33

+0

@Nawaz这有帮助...关心扩大?我也愿意学习。 – Dennis 2011-05-10 08:27:55

+0

@ Dennis:'_out_newStr'是一个指向'std :: string'的指针,你怎么能给它分配字符文字?你的代码甚至不会编译。 – Nawaz 2011-05-10 08:29:31

0

如何:

printf("%s", foo.c_str()); 

或者更好的,忘了使用字符指针。

+2

'std :: cout << foo()'如何? :d – Nawaz 2011-05-10 08:25:19