Differences in use of c_str() when returning a value from a function
如果我有以下两个功能
1 2 3 4 5 6 | std::string foo1() { std::string temp; ... return temp; } |
和
1 2 3 4 5 6 | const char* foo2() { std::string temp; ... return temp.c_str(); } |
和一个以const char *作为输入的函数;
1 | void bar(const char* input) { ... } |
哪个更安全:
1 | bar(foo1().c_str()); |
要么
1 | bar(foo2()); |
如果我要做的只是将字符串作为输入传递给bar,然后不关心
1 2 3 4 5 6 | const char* foo2() { std::string temp; ... return temp.c_str(); } |
只需使用
1 2 3 4 5 6 | std::string foo1() { std::string temp; ... return temp; } |
1 2 3 4 5 6 | const char* foo2() { std::string temp; ... return temp.c_str(); } |
根本不安全,因为
只要未破坏原始字符串对象,c_str的字符数组就有效。这已经被问过了。在函数的最后,
bar(foo2());简直是错误的……因为当foo2返回时,temp std :: string被破坏,并且c_str()返回的指针现在指向无效的位置。