问题描述
C ++ 17将包含,一种用于原子可寻址单元的类型,在典型计算机上具有8位。
C++17 will include std::byte
, a type for one atomically-addressable unit of memory, having 8 bits on typical computers.
在此标准化之前,已经存在指向原始内存时遇到了一些难题-一方面使用 char *
/ unsigned char *
void *
。现在,删除了 void *
的原因之一- std :: byte
的含义与 char
;
Before this standardization, there is already a bit of dilemma when pointing into "raw" memory - between using char*
/unsigned char*
on one hand or void *
on the other. Now, one of reasons for prefering void *
is removed - std::byte
does not have the same connotations as a char
; it's about raw memory, not characters.
因此,我的问题是:在 std的日子里,有什么好的经验法则:字节
,关于何时更喜欢它而不是 void *
,以及何时相反?
So, my question is: What is a good rule of thumb, for the days of std::byte
, regarding when to prefer it over void *
and when it's the other way around?
推荐答案
(这是潜在的经验法则从我的头顶上掉下来,没有被任何人宽恕。)
(This is a potential rule of thumb which comes off the top of my head, not condoned by anyone.)
- 将
char *
用于文本字符序列,没有其他内容。 - 在类型擦除设置中使用
void *
,即当键入指向的数据,但是由于某种原因,不能使用键入的指针,或者无法确定是否键入了该指针。 - 使用
字节*
用于原始内存,没有迹象表明它保存有任何类型的数据。
- Use
char *
for sequences of textual characters, not anything else. - Use
void *
in type-erasure settings, i.e. when the pointed-to data is typed, but for some reason a typed pointer must not be used or it cannot be determined whether it's typed or not. - Use
byte *
for raw memory for which there is no indication of it holding any typed data.
上述例外:
- 也可以使用
void *
/char *
(如果年龄较大或使用非C ++强制使用),否则您将使用byte *
-bu请尽可能紧密地使用基于byte *
的接口包装该接口,而不是将其暴露给其余的C ++代码。
- Also use
void *
/char *
when older or non-C++ forces you and you would otherwise usebyte *
- but wrap that with abyte *
-based interface as tightly as you can rather than exposing it to the rest of your C++ code.
void * my_custom_malloc(size_t size)
- 错误
byte * my_custom_malloc(size_t大小)
-正确
struct buffer_t {字节*数据; size_t长度; my_type_t data_type; }
-错误
struct buffer_t {void * data; size_t长度; my_type_t data_type; }
-右
这篇关于在std :: byte标准化的情况下,什么时候使用void *和什么时候使用byte *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!