本文介绍了什么时候使用std :: string vs char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,但是我确实更喜欢C ++.

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

我有一个抽象类,它定义了两个常量字符串(不是静态的).我想知道 const char * 是否会是更好的选择.我仍然掌握C ++标准,但我只是想真的没有任何理由在这种特殊情况下需要使用std :: string(无需追加或编辑字符串,只需将其写入通过 printf 控制台).

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).

在每种情况下我都应该坚持使用 std :: string 吗?

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

推荐答案

在每种情况下我都应该坚持使用std :: string吗?

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

是的

除了在少数情况下,您编写高性能的多线程日志记录库,您确实需要知道何时进行内存分配,或者可能是在某些情况下摆弄了数据包头中的各个位低级协议/驱动程序.

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.

问题是,您从一个简单的char开始,然后需要打印它,因此您使用printf(),然后使用sprintf()对其进行解析,因为std :: stream仅对一个int来说会很痛苦串起来.最终您会得到不安全且无法维护的oc c/c ++混合

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++

这篇关于什么时候使用std :: string vs char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:51