std :: string或std :: vector< char>以保存原始数据 [英] std::string or std::vector<char> to hold raw data

查看:291
本文介绍了std :: string或std :: vector< char>以保存原始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个问题是适合stackoverflow ...存储原始数据字节(8位)在 std :: string 之间的区别,而不是存储它们在 std :: vector< char> 中。我从一个文件读取二进制数据,并将这些原始字节存储在 std :: string 。这工作很好,没有问题或问题这样做。我的程序按预期工作。然而,其他程序员喜欢 std :: vector< char> 方法,建议我停止使用 std :: string 它对原始字节不安全。所以我想知道为什么使用 std :: string 来保存原始数据字节是不安全的?我知道 std :: string 最常用来存储ASCII文本,但一个字节是一个字节,所以我不明白 std :: vector< char>

I hope this question is appropriate for stackoverflow... What is the difference between storing raw data bytes (8 bits) in a std::string rather than storing them in std::vector<char>. I'm reading binary data from a file and storing those raw bytes in a std::string. This works well, there are no problems or issues with doing this. My program works as expected. However, other programmers prefer the std::vector<char> approach and suggest I stop using std::string as it's unsafe for raw bytes. So I'm wondering why might it be unsafe to use std::string to hold raw data bytes? I know std::string is most often used to store ASCII text, but a byte is a byte, so I don't understand the preference of the std::vector<char>.

感谢您的任何意见!

推荐答案

问题不在于它是否工作,或者它不是。问题是,它是完全混乱的下一个人读你的代码。 std :: string 用于显示文本。任何人阅读你的代码将期望。您将使用 std :: vector< char> 更好地声明您的意图

The problem is not really whether it works or it doesn't. The problem is that it is utterly confusing for the next guy reading your code. std::string is meant for displaying text. Anybody reading your code will expect that. You'll declare your intent much better with a std::vector<char>.

它会增加代码审查中的 WTF / min

It increases your WTF/min in code reviews.

这篇关于std :: string或std :: vector&lt; char&gt;以保存原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆