When to use std::string vs char*? [duplicate]

2020-06-16 03:18发布

Possible Duplicate:
C++ char* vs std::string

I'm new to C++ coming from C# but I really do like C++ much better.

I have an abstract class that defines two constant strings (not static). And I wondered if a const char* would be a better choice. I'm still getting the hang of the C++ standards, but I just figured that there really isn't any reason why I would need to use std::string in this particular case (no appending or editing the string, just writing to the console via printf).

Should I stick to std::string in every case?

标签: c++ std
5条回答
放荡不羁爱自由
2楼-- · 2020-06-16 03:43

Should I stick to std::string in every case?

Yes.

Except perhaps for a few edge cases where you writing a high performance multi-threaded logging lib and you really need to know when a memory allocation is going to take place, or perhaps in fiddling with individual bits in a packet header in some low level protocol/driver.

The problem is that you start with a simple char and then you need to print it, so you use printf(), then perhaps a sprintf() to parse it because std::stream would be a pain for just one int to string. And you end up with an unsafe and unmaintainable mix oc c/c++

查看更多
可以哭但决不认输i
3楼-- · 2020-06-16 03:44

Should I stick to std::string in every case?

There are cases where std::string isn't needed and just a plain char const* will do. However you do get other functionality besides manipulation, you also get to do comparison with other strings and char arrays, and all the standard algorithms to operate on them.

I would say go with std::string by default (for members and variables), and then only change if you happen to see that is the cause of a performance drop (which it won't).

查看更多
一纸荒年 Trace。
4楼-- · 2020-06-16 03:44

This like comparing Apples to Oranges. std::string is a container class while char* is just a pointer to a character sequence.

It really all depends on what you want to do with the string.

Std::string on the other hand can give you a quick access for simple string calculation and manipulation function. Most of those are simple string manipulation functions, nothing fancy really.

So it basically depends on your needs and how your functions are declared. The only advantage for std::string over a char pointer is that it doesnt require a specific lenghth decleration.

查看更多
男人必须洒脱
5楼-- · 2020-06-16 03:46

I would stick to using std::string instead of const char*, simply because most of the built-in C++ libraries work with strings and not character arrays. std::string has a lot of built-in methods and facilities that give the programmer a lot of power when manipulating strings.

查看更多
乱世女痞
6楼-- · 2020-06-16 04:02

Use std::string when you need to store a value.

Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.

查看更多
登录 后发表回答