Why do you prefer char* instead of string, in C++?

后端 未结 12 1280
北海茫月
北海茫月 2021-02-01 08:31

I\'m a C programmer trying to write c++ code. I heard string in C++ was better than char* in terms of security, performance, etc, however sometimes it

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 08:50

    Use std::string for its incredible convenience - automatic memory handling and methods / operators. With some string manipulations, most implementations will have optimizations in place (such as delayed evaluation of several subsequent manipulations - saves memory copying).

    If you need to rely on the specific char layout in memory for other optimizations, try std::vector instead. If you have a non-empty vector vec, you can get a char* pointer using &vec[0] (the vector has to be nonempty).

提交回复
热议问题