gpt4 book ai didi

c++ - 如何拥有类似于 unsigned char 的类型,但不允许别名?

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:27 28 4
gpt4 key购买 nike

我想要一个类型,类似于unsigned char:

  • sizeof 为 1
  • 可以为其分配整数值(无需任何转换)
  • 允许位操作
  • 算术是允许的,但不是必须的
  • 未签名
  • 简单可复制

但是,与 unsigned char 不同的是,它不允许别名。我的意思是,一种类型,它没有异常 [basic.lval/11.8] :

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

[...]

  • a char, unsigned char, or std​::​byte type.

有没有可能有这样的类型?

原因:我几乎从不使用unsigned char 的别名属性。所以,我想改用一种类型,它不会阻止某些类型的优化(注意,我问这个问题是因为我实际上有一些函数,由于 无符号字符)。所以,我想要一个类型,它是真的:“不要为你不用的东西付费”。


这是一个示例,其中 unsigned char 阻止了优化:Using this pointer causes strange deoptimization in hot loop

最佳答案

标准的该部分调用了 charunsigned charstd::byte。但是,您可以创建自己的类型,如 std::byte 并且不允许使用别名:

enum class my_byte : unsigned char {};

使用它不是很好,因为您必须转换为 unsigned char 才能用它做任何有意义的事情。但是,您可以重载按位运算符和算术运算符,使其更易于使用。


我们可以用下面的简单函数来验证这一点:

auto foo(A& a, B& b) {
auto lhs = b;
a = 42;
auto rhs = b;
return lhs + rhs;
}

如果 A 被允许使用 B 作为别名,编译器将不得不生成两个负载:一个用于 lhs,一个用于 右手边。如果不允许 AB 进行别名,则编译器可以生成单个加载并将该值添加到自身。 Let's test it :

// int& cannot alias with long&
auto foo(int& a, long& b) {
auto lhs = b;
a = 42;
auto rhs = b;
return lhs + rhs;
}

// std::byte& can alias with long&
auto bar(std::byte& a, long& b) {
auto lhs = b;
a = (std::byte)42;
auto rhs = b;
return lhs + rhs;
}

// if my_byte& can alias with long&, there would have to be two loads
auto baz(my_byte& a, long& b) {
auto lhs = b;
a = (my_byte)42;
auto rhs = b;
return lhs + rhs;
}

结果如下:

foo(int&, long&):
mov rax, QWORD PTR [rsi]
mov DWORD PTR [rdi], 42
add rax, rax
ret
bar(std::byte&, long&):
mov rax, QWORD PTR [rsi]
mov BYTE PTR [rdi], 42
add rax, QWORD PTR [rsi]
ret
baz(my_byte&, long&):
mov rax, QWORD PTR [rsi]
mov BYTE PTR [rdi], 42
add rax, rax
ret

因此 my_byte 不继承与 charstd::byte 相同的别名属性

关于c++ - 如何拥有类似于 unsigned char 的类型,但不允许别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52239039/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com