当您必须将 std::string 作为 char* 传递时, std::string 是否比 char* 更好?
在 最近的问题,我了解到在某些情况下您只需传递 char*
而不是 std::string
。我真的很喜欢 string
,对于只需要传递不可变字符串的情况,使用 .c_str()
效果很好。在我看来,利用字符串类的易于操作性是个好主意。然而,对于需要输入的函数,我最终会做这样的事情:
std::string str;
char* cstr = new char[500]; // I figure dynamic allocation is a good idea just
getstr(cstr); // in case I want the user to input the limit or
str = cstr; // something. Not sure if it matters.
delete[] cstr;
printw(str.c_str());
显然,这并不是那么简单。现在,我对 C++ 还很陌生,所以我不能真正只见树木。在这样的情况下,每个输入都必须转换为 C 字符串,然后再转换回来,才能利用 string
的有用方法,那么是否是一个更好的主意?习惯 C 风格的字符串操作吗?这种不断地来回转换是不是太愚蠢了?
In a recent question, I learned that there are situations where you just gotta pass a char*
instead of a std::string
. I really like string
, and for situations where I just need to pass an immutable string, it works fine to use .c_str()
. The way I see it, it's a good idea to take advantage of the string class for its ease of manipulation. However, for functions that require an input, I end up doing something like this:
std::string str;
char* cstr = new char[500]; // I figure dynamic allocation is a good idea just
getstr(cstr); // in case I want the user to input the limit or
str = cstr; // something. Not sure if it matters.
delete[] cstr;
printw(str.c_str());
Obviously, this isn't so, uh, straightforward. Now, I'm pretty new to C++ so I can't really see the forest for the trees. In a situation like this, where every input is going to have to get converted to a C string and back to take advantage of string
's helpful methods, is it just a better idea to man up and get used to C-style string manipulation? Is this kind of constant back-and-forth conversion too stupid to deal with?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您给出的示例中,您通常可以使用
std::getline
函数将一行读入std::string
中: http://www.cplusplus.com/reference/string/getline/当然,这并不能完成诅咒库的所有工作做。如果您需要一个非常量
char*
以便某些 C 函数可以读取它,则可以使用vector
。您可以从string
创建一个vector
,反之亦然:因此您的示例变为:
In the example you give, you can generally read a line into a
std::string
using thestd::getline
function: http://www.cplusplus.com/reference/string/getline/Of course this doesn't do everything that a curses library does. If you need a non-const
char*
so that some C function can read into it, you can use avector<char>
. You can create avector<char>
from astring
, and vice-versa:So your example becomes:
大多数 std::string::c_str() 实现(如果不是全部)只是返回一个指向内部缓冲区的指针。没有任何开销。
但请注意,c_str() 返回一个
const char*
,而不是 char*。并且该指针在函数调用后将失效。因此,如果函数执行诸如写回传递的字符串或复制指针之类的操作,则不能使用它。Most std::string::c_str() implementations (if not all of them) simply return a pointer to an internal buffer. No overhead whatsoever.
Beware however that c_str() returns a
const char*
, not a char*. And that the pointer will become invalid after the function call. So you cannot use it if the function does anything like writing back into the passed string or makes a copy of the pointer.